"use client"

// Shared list/create/deactivate screen for the plain "code + name" HRM masters
// (Branch, Designation, EmploymentType) — identical shape to each other, so one
// component parameterized by the resource's api/labels replaces 3 near-duplicate pages.
import { useEffect, useState } from "react"
import { Plus } from "lucide-react"

import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { ApiResult, EntityStatus, PaginationMeta } from "@/types/common"

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 { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { toast } from "@/components/ui/toast"

interface CodeNamed {
  code: string
  name: string
  status: EntityStatus
}

interface Api<T extends CodeNamed> {
  list(params: { page: number; pageSize: number }): Promise<{ items: T[]; pagination: PaginationMeta }>
  create(request: { code: string; name: string }): Promise<ApiResult<T>>
  updateStatus(id: number, status: EntityStatus): Promise<void>
}

export function CodeNameMasterPage<T extends CodeNamed>({
  title,
  description,
  idOf,
  api,
}: {
  title: string
  description: string
  idOf: (item: T) => number
  api: Api<T>
}) {
  const PAGE_SIZE = 10
  const [items, setItems] = useState<T[] | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  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 [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

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

  useEffect(load, [page]) // eslint-disable-line react-hooks/exhaustive-deps

  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 api.create({ code: code.trim(), name: name.trim() })
      toast.success(`${title.replace(/s$/, "")} created`)
      setOpen(false)
      setCode("")
      setName("")
      setErrors({})
      load()
    } catch (err) {
      toast.error("Could not create", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  async function toggleStatus(item: T) {
    const next: EntityStatus = item.status === "Active" ? "Inactive" : "Active"
    try {
      await api.updateStatus(idOf(item), next)
      load()
    } catch (err) {
      toast.error("Could not update status", errorMessage(err))
    }
  }

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">{title}</h1>
          <p className="text-base text-muted-foreground">{description}</p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger render={<Button size="lg"><Plus className="size-5" />New</Button>} />
          <DialogContent className="sm:max-w-sm">
            <DialogHeader className="items-center text-center">
              <DialogTitle>New {title.replace(/s$/, "")}</DialogTitle>
              <DialogDescription>Deactivate later — masters are never deleted.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <Field data-invalid={!!errors.code}>
                <FieldLabel htmlFor="m-code">Code</FieldLabel>
                <Input id="m-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="m-name">Name</FieldLabel>
                <Input id="m-name" value={name} onChange={(e) => setName(e.target.value)} aria-invalid={!!errors.name} />
                <FieldError errors={[errors.name ? { message: errors.name } : undefined]} />
              </Field>
            </FieldGroup>
            <div className="flex justify-center gap-3 pt-2">
              <Button variant="outline" className="min-w-32" onClick={() => setOpen(false)} disabled={submitting}>Cancel</Button>
              <Button className="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 records 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">Status</TableHead>
              <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.map((item) => (
              <TableRow key={idOf(item)}>
                <TableCell className="px-3 py-3.5 font-medium">{item.code}</TableCell>
                <TableCell className="px-3 py-3.5">{item.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", item.status === "Active" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground")}>
                    {item.status}
                  </Badge>
                </TableCell>
                <TableCell className="px-3 py-3.5">
                  <Button variant="ghost" size="sm" onClick={() => toggleStatus(item)}>
                    {item.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>
  )
}
