"use client"

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

import { leaveTypesApi } from "@/lib/api/hrm-masters"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { PaginationMeta } from "@/types/common"
import { LeaveType } from "@/types/hrm"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
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"

const PAGE_SIZE = 10

export default function LeaveTypesPage() {
  const [items, setItems] = useState<LeaveType[] | 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 [isPaid, setIsPaid] = useState(true)
  const [countsAsNoPay, setCountsAsNoPay] = useState(false)
  const [accrualPerYear, setAccrualPerYear] = useState(14)
  const [carryForwardAllowed, setCarryForwardAllowed] = useState(false)
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

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

  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 leaveTypesApi.create({
        code: code.trim(), name: name.trim(), isPaid, countsAsNoPay, accrualPerYear,
        carryForwardAllowed, requiresApproval: true,
      })
      toast.success("Leave type created")
      setOpen(false)
      setCode("")
      setName("")
      load()
    } catch (err) {
      toast.error("Could not create leave type", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  async function toggleStatus(item: LeaveType) {
    try {
      await leaveTypesApi.updateStatus(item.leaveTypeId, 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">Leave Types</h1>
          <p className="text-base text-muted-foreground">Annual, Casual, Medical, Unpaid, etc. — drives Attendance&apos;s OnLeave classification and Payroll&apos;s No-Pay calc.</p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger render={<Button size="lg"><Plus className="size-5" />New Leave Type</Button>} />
          <DialogContent className="sm:max-w-sm">
            <DialogHeader className="items-center text-center">
              <DialogTitle>New Leave Type</DialogTitle>
              <DialogDescription>Whether it&apos;s paid affects payroll&apos;s No-Pay deduction.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <Field data-invalid={!!errors.code}>
                <FieldLabel htmlFor="lt-code">Code</FieldLabel>
                <Input id="lt-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="lt-name">Name</FieldLabel>
                <Input id="lt-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="lt-accrual">Days per year</FieldLabel>
                <Input id="lt-accrual" type="number" min={0} value={accrualPerYear} onChange={(e) => setAccrualPerYear(Number(e.target.value))} />
              </Field>
              <Field orientation="horizontal">
                <Checkbox id="lt-paid" checked={isPaid} onCheckedChange={(v) => setIsPaid(v === true)} />
                <FieldLabel htmlFor="lt-paid">Paid leave</FieldLabel>
              </Field>
              <Field orientation="horizontal">
                <Checkbox id="lt-nopay" checked={countsAsNoPay} onCheckedChange={(v) => setCountsAsNoPay(v === true)} />
                <FieldLabel htmlFor="lt-nopay">Counts as No-Pay in payroll</FieldLabel>
              </Field>
              <Field orientation="horizontal">
                <Checkbox id="lt-carry" checked={carryForwardAllowed} onCheckedChange={(v) => setCarryForwardAllowed(v === true)} />
                <FieldLabel htmlFor="lt-carry">Carry-forward allowed</FieldLabel>
              </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 leave types 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">Days/yr</TableHead>
              <TableHead className="h-12 px-3 text-sm">Paid</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((t) => (
              <TableRow key={t.leaveTypeId}>
                <TableCell className="px-3 py-3.5 font-medium">{t.code}</TableCell>
                <TableCell className="px-3 py-3.5">{t.name}</TableCell>
                <TableCell className="px-3 py-3.5">{t.accrualPerYear}</TableCell>
                <TableCell className="px-3 py-3.5">{t.isPaid ? "Yes" : "No"}</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", t.status === "Active" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground")}>{t.status}</Badge>
                </TableCell>
                <TableCell className="px-3 py-3.5">
                  <Button variant="ghost" size="sm" onClick={() => toggleStatus(t)}>{t.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>
  )
}
