"use client"

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

import { attendanceApi } from "@/lib/api/attendance"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { AttendanceRecord, AttendanceUploadBatch } 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"

const ROW_STATUS_STYLE: Record<AttendanceRecord["rowValidationStatus"], string> = {
  Valid: "bg-success/10 text-success",
  DuplicateWithinBatch: "bg-warning/10 text-warning",
  DuplicateConfirmed: "bg-warning/10 text-warning",
  EmployeeNotFound: "bg-destructive/10 text-destructive",
  InvalidDateTime: "bg-destructive/10 text-destructive",
  Error: "bg-destructive/10 text-destructive",
}

function minutesLabel(m: number): string {
  if (m <= 0) return "0"
  const h = Math.floor(m / 60)
  const mm = m % 60
  return h > 0 ? `${h}h ${mm}m` : `${mm}m`
}

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

  const [batch, setBatch] = useState<AttendanceUploadBatch | null>(null)
  const [records, setRecords] = useState<AttendanceRecord[] | null>(null)
  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([attendanceApi.get(batchId), attendanceApi.listRecords(batchId)])
      .then(([b, r]) => { setBatch(b); setRecords(r) })
      .catch((err) => setError(errorMessage(err)))
  }
  useEffect(load, [batchId])

  const locked = batch?.status === "Confirmed" || batch?.status === "UsedInPayroll"

  async function resolve(recordId: number, action: "keep" | "discard" | "supersede") {
    try {
      await attendanceApi.resolveDuplicate(batchId, recordId, action)
      toast.success("Resolved")
      load()
    } catch (err) {
      toast.error("Could not resolve", errorMessage(err))
    }
  }

  async function validate() {
    setBusy(true)
    try {
      const b = await attendanceApi.validate(batchId)
      setBatch(b)
      toast.success("Batch validated")
    } catch (err) {
      toast.error("Could not validate", errorMessage(err))
    } finally {
      setBusy(false)
    }
  }

  async function confirm() {
    setBusy(true)
    try {
      const b = await attendanceApi.confirm(batchId)
      setBatch(b)
      toast.success("Batch confirmed", "This is now the source of truth for payroll.")
    } catch (err) {
      toast.error("Could not confirm", errorMessage(err))
    } finally {
      setBusy(false)
    }
  }

  async function unlock() {
    if (!unlockReason.trim()) { toast.error("A reason is required"); return }
    setBusy(true)
    try {
      const b = await attendanceApi.unlock(batchId, unlockReason.trim())
      setBatch(b)
      setUnlockOpen(false)
      setUnlockReason("")
      toast.success("Batch unlocked")
    } catch (err) {
      toast.error("Could not unlock", 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 (!batch || !records) return <div className="flex flex-col gap-3">{Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-14 w-full" />)}</div>

  const unresolved = records.filter((r) => r.rowValidationStatus !== "Valid")

  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">{batch.docNo}</h1>
          <p className="text-base text-muted-foreground">{new Date(batch.periodStart).toLocaleDateString()} – {new Date(batch.periodEnd).toLocaleDateString()} · {batch.rowCountTotal} rows</p>
        </div>
        <div className="flex items-center gap-3">
          <Badge variant="outline" className="h-7 px-3 text-sm">{batch.status}</Badge>
          {batch.status === "Draft" && <Button onClick={validate} disabled={busy || unresolved.length > 0}>Validate</Button>}
          {batch.status === "Validated" && <Button onClick={confirm} disabled={busy}>Confirm</Button>}
          {batch.status === "Confirmed" && (
            <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 batch</DialogTitle>
                  <DialogDescription>Requires a reason and reverts to Validated for editing.</DialogDescription>
                </DialogHeader>
                <FieldGroup>
                  <Field><FieldLabel htmlFor="u-reason">Reason</FieldLabel><Input id="u-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>

      {unresolved.length > 0 && batch.status === "Draft" && (
        <div className="rounded-lg border border-warning/30 bg-warning/5 p-4 text-sm text-warning">
          {unresolved.length} record(s) have unresolved errors or duplicates — resolve them before validating.
        </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">Date</TableHead>
            <TableHead className="h-12 px-3 text-sm">In / Out</TableHead>
            <TableHead className="h-12 px-3 text-sm">Working Hours</TableHead>
            <TableHead className="h-12 px-3 text-sm">Late</TableHead>
            <TableHead className="h-12 px-3 text-sm">OT</TableHead>
            <TableHead className="h-12 px-3 text-sm">Status</TableHead>
            <TableHead className="h-12 px-3 text-sm">Row</TableHead>
            {!locked && <TableHead className="h-12 px-3 text-sm">Resolve</TableHead>}
          </TableRow>
        </TableHeader>
        <TableBody>
          {records.map((r) => (
            <TableRow key={r.attendanceRecordId}>
              <TableCell className="px-3 py-3.5">{r.employeeName ?? r.employeeCode ?? "Unknown"}</TableCell>
              <TableCell className="px-3 py-3.5">{new Date(r.attendanceDate).toLocaleDateString()}</TableCell>
              <TableCell className="px-3 py-3.5">{r.checkIn?.slice(0, 5) ?? "—"} / {r.checkOut?.slice(0, 5) ?? "—"}</TableCell>
              <TableCell className="px-3 py-3.5">{minutesLabel(r.workingMinutes)}</TableCell>
              <TableCell className="px-3 py-3.5">{r.lateMinutes > 0 ? `${r.lateMinutes} min` : "0"}</TableCell>
              <TableCell className="px-3 py-3.5">{r.overtimeMinutes > 0 ? minutesLabel(r.overtimeMinutes) : "0"}</TableCell>
              <TableCell className="px-3 py-3.5">{r.attendanceStatus}</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", ROW_STATUS_STYLE[r.rowValidationStatus])}>{r.rowValidationStatus}</Badge>
              </TableCell>
              {!locked && (
                <TableCell className="px-3 py-3.5">
                  {r.rowValidationStatus !== "Valid" && r.rowValidationStatus !== "EmployeeNotFound" && (
                    <div className="flex gap-1">
                      <Button variant="ghost" size="sm" onClick={() => resolve(r.attendanceRecordId, "keep")}>Keep</Button>
                      <Button variant="ghost" size="sm" onClick={() => resolve(r.attendanceRecordId, "discard")}>Discard</Button>
                    </div>
                  )}
                </TableCell>
              )}
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  )
}
