"use client"

import { useEffect, useState } from "react"
import { Plus } from "lucide-react"

import { departmentsApi, branchesHrmApi } from "@/lib/api/hrm-masters"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { PaginationMeta } from "@/types/common"
import { Branch, Department } from "@/types/hrm"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { toast } from "@/components/ui/toast"

const PAGE_SIZE = 10
const NONE = "__none__"

export default function DepartmentsPage() {
  const [items, setItems] = useState<Department[] | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [branches, setBranches] = useState<Branch[]>([])
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)

  const [open, setOpen] = useState(false)
  const [code, setCode] = useState("")
  const [name, setName] = useState("")
  const [parentDepartmentId, setParentDepartmentId] = useState(NONE)
  const [branchId, setBranchId] = useState(NONE)
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  function load() {
    departmentsApi
      .list({ page, pageSize: PAGE_SIZE })
      .then((res) => {
        setItems(res.items)
        setPagination(res.pagination)
      })
      .catch((err) => setError(errorMessage(err)))
  }

  useEffect(load, [page])
  useEffect(() => {
    branchesHrmApi.list({ pageSize: 200, status: "Active" }).then((res) => setBranches(res.items)).catch(() => setBranches([]))
  }, [])

  async function handleCreate() {
    const nextErrors: Record<string, string> = {}
    if (!code.trim()) nextErrors.code = "Code is required"
    if (!name.trim()) nextErrors.name = "Name is required"
    setErrors(nextErrors)
    if (Object.keys(nextErrors).length > 0) return

    setSubmitting(true)
    try {
      await departmentsApi.create({
        code: code.trim(),
        name: name.trim(),
        parentDepartmentId: parentDepartmentId === NONE ? null : Number(parentDepartmentId),
        branchId: branchId === NONE ? null : Number(branchId),
      })
      toast.success("Department created")
      setOpen(false)
      setCode("")
      setName("")
      setParentDepartmentId(NONE)
      setBranchId(NONE)
      load()
    } catch (err) {
      toast.error("Could not create department", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  async function toggleStatus(item: Department) {
    try {
      await departmentsApi.updateStatus(item.departmentId, item.status === "Active" ? "Inactive" : "Active")
      load()
    } catch (err) {
      toast.error("Could not update status", errorMessage(err))
    }
  }

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Departments</h1>
          <p className="text-base text-muted-foreground">Org structure — unlimited nesting, optionally scoped to a branch.</p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger render={<Button size="lg"><Plus className="size-5" />New Department</Button>} />
          <DialogContent className="sm:max-w-sm">
            <DialogHeader className="items-center text-center">
              <DialogTitle>New Department</DialogTitle>
              <DialogDescription>Set a parent department for a sub-department, or leave it top-level.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <Field data-invalid={!!errors.code}>
                <FieldLabel htmlFor="d-code">Code</FieldLabel>
                <Input id="d-code" value={code} onChange={(e) => setCode(e.target.value)} aria-invalid={!!errors.code} />
                <FieldError errors={[errors.code ? { message: errors.code } : undefined]} />
              </Field>
              <Field data-invalid={!!errors.name}>
                <FieldLabel htmlFor="d-name">Name</FieldLabel>
                <Input id="d-name" value={name} onChange={(e) => setName(e.target.value)} aria-invalid={!!errors.name} />
                <FieldError errors={[errors.name ? { message: errors.name } : undefined]} />
              </Field>
              <Field>
                <FieldLabel htmlFor="d-parent">Parent department (optional)</FieldLabel>
                <Select value={parentDepartmentId} onValueChange={(v) => setParentDepartmentId(v ?? NONE)}>
                  <SelectTrigger id="d-parent"><SelectValue placeholder="None" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value={NONE}>None</SelectItem>
                    {(items ?? []).map((d) => (
                      <SelectItem key={d.departmentId} value={String(d.departmentId)}>{d.name}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </Field>
              <Field>
                <FieldLabel htmlFor="d-branch">Branch (optional)</FieldLabel>
                <Select value={branchId} onValueChange={(v) => setBranchId(v ?? NONE)}>
                  <SelectTrigger id="d-branch"><SelectValue placeholder="None" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value={NONE}>None</SelectItem>
                    {branches.map((b) => (
                      <SelectItem key={b.branchId} value={String(b.branchId)}>{b.name}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </Field>
            </FieldGroup>
            <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-center">
              <Button variant="outline" className="w-full sm:w-auto sm:min-w-32" onClick={() => setOpen(false)} disabled={submitting}>Cancel</Button>
              <Button className="w-full sm:w-auto sm:min-w-32" onClick={handleCreate} disabled={submitting}>{submitting ? "Creating…" : "Create"}</Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {error && <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{error}</div>}
      {!error && items === null && <div className="flex flex-col gap-3">{Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-14 w-full" />)}</div>}
      {!error && items !== null && items.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <p className="text-base text-muted-foreground">No departments yet.</p>
        </div>
      )}
      {!error && items !== null && items.length > 0 && (
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">Code</TableHead>
              <TableHead className="h-12 px-3 text-sm">Name</TableHead>
              <TableHead className="h-12 px-3 text-sm">Parent</TableHead>
              <TableHead className="h-12 px-3 text-sm">Status</TableHead>
              <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.map((d) => (
              <TableRow key={d.departmentId}>
                <TableCell className="px-3 py-3.5 font-medium">{d.code}</TableCell>
                <TableCell className="px-3 py-3.5">{d.name}</TableCell>
                <TableCell className="px-3 py-3.5">{items.find((p) => p.departmentId === d.parentDepartmentId)?.name ?? "—"}</TableCell>
                <TableCell className="px-3 py-3.5">
                  <Badge variant="outline" className={cn("h-6 w-fit justify-center border-transparent px-2.5 text-sm", d.status === "Active" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground")}>{d.status}</Badge>
                </TableCell>
                <TableCell className="px-3 py-3.5">
                  <Button variant="ghost" size="sm" onClick={() => toggleStatus(d)}>{d.status === "Active" ? "Deactivate" : "Activate"}</Button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
      {pagination && pagination.totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">Showing {(pagination.page - 1) * pagination.pageSize + 1}–{Math.min(pagination.page * pagination.pageSize, pagination.totalItems)} of {pagination.totalItems}</p>
          <div className="flex items-center gap-2">
            <Button type="button" variant="outline" size="sm" disabled={pagination.page <= 1} onClick={() => setPage((p) => Math.max(1, p - 1))}>Previous</Button>
            <span className="text-sm text-muted-foreground">Page {pagination.page} of {pagination.totalPages}</span>
            <Button type="button" variant="outline" size="sm" disabled={pagination.page >= pagination.totalPages} onClick={() => setPage((p) => Math.min(pagination.totalPages, p + 1))}>Next</Button>
          </div>
        </div>
      )}
    </div>
  )
}
