"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { Eye, Plus } from "lucide-react"

import { payrollRunsApi } from "@/lib/api/payroll"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { PaginationMeta } from "@/types/common"
import { PayrollRun, PayrollRunStatus } from "@/types/hrm"

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

const STATUS_STYLE: Record<PayrollRunStatus, string> = {
  Draft: "bg-muted text-muted-foreground",
  Approved: "bg-warning/10 text-warning",
  Locked: "bg-success/10 text-success",
}

export default function PayrollRunsPage() {
  const [runs, setRuns] = useState<PayrollRun[] | 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 now = new Date()
  const [periodYear, setPeriodYear] = useState(now.getFullYear())
  const [periodMonth, setPeriodMonth] = useState(now.getMonth() + 1)
  const [submitting, setSubmitting] = useState(false)

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

  async function handleGenerate() {
    setSubmitting(true)
    try {
      await payrollRunsApi.generate({ periodYear, periodMonth })
      toast.success("Payroll run generated")
      setOpen(false)
      load()
    } catch (err) {
      toast.error("Could not generate payroll", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  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">Payroll</h1>
          <p className="text-base text-muted-foreground">Generate → Review → Approve → Lock → Payslips.</p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger render={<Button size="lg"><Plus className="size-5" />Generate Payroll</Button>} />
          <DialogContent className="sm:max-w-sm">
            <DialogHeader className="items-center text-center">
              <DialogTitle>Generate Payroll Run</DialogTitle>
              <DialogDescription>Blocked if attendance for this period isn&apos;t fully Confirmed yet.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <Field><FieldLabel>Year</FieldLabel><Input type="number" value={periodYear} onChange={(e) => setPeriodYear(Number(e.target.value))} /></Field>
                <Field><FieldLabel>Month</FieldLabel><Input type="number" min={1} max={12} value={periodMonth} onChange={(e) => setPeriodMonth(Number(e.target.value))} /></Field>
              </div>
            </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={handleGenerate} disabled={submitting}>{submitting ? "Generating…" : "Generate"}</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 && runs === null && <div className="flex flex-col gap-3">{Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-14 w-full" />)}</div>}
      {!error && runs !== null && runs.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 payroll runs yet.</p></div>
      )}
      {!error && runs !== null && runs.length > 0 && (
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">Doc No</TableHead>
              <TableHead className="h-12 px-3 text-sm">Period</TableHead>
              <TableHead className="h-12 px-3 text-sm">Employees</TableHead>
              <TableHead className="h-12 px-3 text-sm">Gross</TableHead>
              <TableHead className="h-12 px-3 text-sm">Net</TableHead>
              <TableHead className="h-12 px-3 text-sm">Status</TableHead>
              <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {runs.map((r) => (
              <TableRow key={r.payrollRunId}>
                <TableCell className="px-3 py-3.5 font-medium">{r.docNo}</TableCell>
                <TableCell className="px-3 py-3.5">{r.periodMonth.toString().padStart(2, "0")}/{r.periodYear}</TableCell>
                <TableCell className="px-3 py-3.5">{r.employeeCount}</TableCell>
                <TableCell className="px-3 py-3.5">{r.totalGross.toLocaleString(undefined, { minimumFractionDigits: 2 })}</TableCell>
                <TableCell className="px-3 py-3.5">{r.totalNet.toLocaleString(undefined, { minimumFractionDigits: 2 })}</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", STATUS_STYLE[r.status])}>{r.status}</Badge></TableCell>
                <TableCell className="px-3 py-3.5">
                  <Link href={`/dashboard/hrm/payroll/${r.payrollRunId}`} className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }))} aria-label="View"><Eye className="size-4" /></Link>
                </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>
  )
}
