"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { useParams } from "next/navigation"

import { payrollRunsApi, payslipViewUrl } from "@/lib/api/payroll"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { PayrollLine, PayrollRun, Payslip } from "@/types/hrm"

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

function money(n: number): string {
  return n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

export default function PayrollRunDetailPage() {
  const params = useParams<{ id: string }>()
  const runId = Number(params.id)

  const [run, setRun] = useState<PayrollRun | null>(null)
  const [lines, setLines] = useState<PayrollLine[] | null>(null)
  const [payslips, setPayslips] = useState<Payslip[]>([])
  const [error, setError] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)
  const [unlockOpen, setUnlockOpen] = useState(false)
  const [unlockReason, setUnlockReason] = useState("")

  function load() {
    Promise.all([payrollRunsApi.get(runId), payrollRunsApi.listLines(runId)])
      .then(([r, l]) => { setRun(r); setLines(l) })
      .catch((err) => setError(errorMessage(err)))
  }
  useEffect(load, [runId])

  async function approve() {
    setBusy(true)
    try { setRun(await payrollRunsApi.approve(runId)); toast.success("Payroll approved") }
    catch (err) { toast.error("Could not approve", errorMessage(err)) }
    finally { setBusy(false) }
  }

  async function lock() {
    setBusy(true)
    try { setRun(await payrollRunsApi.lock(runId)); toast.success("Payroll locked") }
    catch (err) { toast.error("Could not lock", errorMessage(err)) }
    finally { setBusy(false) }
  }

  async function unlock() {
    if (!unlockReason.trim()) { toast.error("A reason is required"); return }
    setBusy(true)
    try {
      setRun(await payrollRunsApi.unlock(runId, unlockReason.trim()))
      setUnlockOpen(false)
      setUnlockReason("")
      toast.success("Payroll unlocked")
    } catch (err) {
      toast.error("Could not unlock", errorMessage(err))
    } finally {
      setBusy(false)
    }
  }

  async function generatePayslips() {
    setBusy(true)
    try {
      const result = await payrollRunsApi.generatePayslips(runId)
      setPayslips(result)
      toast.success("Payslips generated")
    } catch (err) {
      toast.error("Could not generate payslips", errorMessage(err))
    } finally {
      setBusy(false)
    }
  }

  if (error) return <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{error}</div>
  if (!run || !lines) return <div className="flex flex-col gap-3">{Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-14 w-full" />)}</div>

  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">{run.docNo}</h1>
          <p className="text-base text-muted-foreground">{run.periodMonth.toString().padStart(2, "0")}/{run.periodYear} · {run.employeeCount} employees</p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <Badge variant="outline" className="h-7 px-3 text-sm">{run.status}</Badge>
          {run.status === "Draft" && <Button onClick={approve} disabled={busy}>Approve</Button>}
          {run.status === "Approved" && <Button onClick={lock} disabled={busy}>Lock Payroll</Button>}
          {run.status === "Locked" && (
            <>
              <Button onClick={generatePayslips} disabled={busy}>Generate Payslips</Button>
              <Dialog open={unlockOpen} onOpenChange={setUnlockOpen}>
                <DialogTrigger render={<Button variant="outline">Unlock</Button>} />
                <DialogContent className="sm:max-w-sm">
                  <DialogHeader className="items-center text-center">
                    <DialogTitle>Unlock payroll</DialogTitle>
                    <DialogDescription>The highest-risk action in this module — requires a reason and is fully audited.</DialogDescription>
                  </DialogHeader>
                  <FieldGroup>
                    <Field><FieldLabel htmlFor="p-reason">Reason</FieldLabel><Input id="p-reason" value={unlockReason} onChange={(e) => setUnlockReason(e.target.value)} /></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={() => setUnlockOpen(false)}>Cancel</Button>
                    <Button className="w-full sm:w-auto sm:min-w-32" onClick={unlock} disabled={busy}>Unlock</Button>
                  </div>
                </DialogContent>
              </Dialog>
            </>
          )}
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
        <div className="rounded-xl border bg-card p-4"><p className="text-sm text-muted-foreground">Gross</p><p className="text-xl font-bold">{money(run.totalGross)}</p></div>
        <div className="rounded-xl border bg-card p-4"><p className="text-sm text-muted-foreground">Net</p><p className="text-xl font-bold">{money(run.totalNet)}</p></div>
        <div className="rounded-xl border bg-card p-4"><p className="text-sm text-muted-foreground">Employees</p><p className="text-xl font-bold">{run.employeeCount}</p></div>
        <div className="rounded-xl border bg-card p-4"><p className="text-sm text-muted-foreground">Deductions</p><p className="text-xl font-bold">{money(run.totalGross - run.totalNet)}</p></div>
      </div>

      <Table className="text-base">
        <TableHeader>
          <TableRow>
            <TableHead className="h-12 px-3 text-sm">Employee</TableHead>
            <TableHead className="h-12 px-3 text-sm">Basic</TableHead>
            <TableHead className="h-12 px-3 text-sm">OT</TableHead>
            <TableHead className="h-12 px-3 text-sm">Allowances</TableHead>
            <TableHead className="h-12 px-3 text-sm">Deductions</TableHead>
            <TableHead className="h-12 px-3 text-sm">Net Salary</TableHead>
            <TableHead className="h-12 px-3 text-sm">Details</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {lines.map((l) => {
            const totalDeductions = l.grossSalary - l.netSalary
            const payslip = payslips.find((p) => p.payrollLineId === l.payrollLineId)
            return (
              <TableRow key={l.payrollLineId}>
                <TableCell className="px-3 py-3.5 font-medium">{l.employeeName} <span className="text-muted-foreground">({l.employeeCode})</span></TableCell>
                <TableCell className="px-3 py-3.5">{money(l.basicSalary)}</TableCell>
                <TableCell className="px-3 py-3.5">{money(l.overtimeAmount)}</TableCell>
                <TableCell className="px-3 py-3.5">{money(l.totalAllowances)}</TableCell>
                <TableCell className="px-3 py-3.5">{money(totalDeductions)}</TableCell>
                <TableCell className="px-3 py-3.5 font-semibold">{money(l.netSalary)}</TableCell>
                <TableCell className="px-3 py-3.5">
                  <div className="flex items-center gap-3">
                    <Link href={`/dashboard/hrm/payroll/${runId}/lines/${l.payrollLineId}`} className="text-primary underline underline-offset-2">Breakdown</Link>
                    {payslip && (
                      <a href={payslipViewUrl(payslip.payslipId)} target="_blank" rel="noreferrer" className={cn("text-primary underline underline-offset-2")}>Payslip</a>
                    )}
                  </div>
                </TableCell>
              </TableRow>
            )
          })}
        </TableBody>
      </Table>
    </div>
  )
}
