"use client"

import Link from "next/link"
import { useRouter } from "next/navigation"
import { useState } from "react"

import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"

import type { PayrollListItem } from "@/features/payroll/types"

type PayrollListProps = {
  payrolls: PayrollListItem[]
}

const monthNames = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December",
]

function formatCurrency(amount: number): string {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "KWD",
    minimumFractionDigits: 3,
    maximumFractionDigits: 3,
  }).format(amount)
}

function getStatusBadge(status: string) {
  const styles: Record<string, string> = {
    DRAFT:    "bg-gray-100 text-gray-700 border border-gray-200",
    APPROVED: "bg-blue-50 text-blue-700 border border-blue-200",
    PAID:     "bg-green-50 text-green-700 border border-green-200",
  }
  return (
    <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${styles[status] ?? styles.DRAFT}`}>
      {status.charAt(0) + status.slice(1).toLowerCase()}
    </span>
  )
}

export default function PayrollList({ payrolls }: PayrollListProps) {
  const router = useRouter()
  const [deleteId, setDeleteId] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  async function handleDelete() {
    if (!deleteId) return
    setLoading(true)
    try {
      const res = await fetch(`/api/payroll/${deleteId}`, { method: "DELETE" })
      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.error || "Failed to delete payroll")
      }
      router.refresh()
    } catch (err) {
      alert(err instanceof Error ? err.message : "Failed to delete")
    } finally {
      setLoading(false)
      setDeleteId(null)
    }
  }

  async function handleProcess(id: string, status: "APPROVED" | "PAID") {
    try {
      const res = await fetch(`/api/payroll/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status }),
      })
      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.error || `Failed to ${status} payroll`)
      }
      router.refresh()
    } catch (err) {
      alert(err instanceof Error ? err.message : "Failed to process")
    }
  }

  if (payrolls.length === 0) {
    return (
      <Card className="p-8 text-center">
        <p className="text-muted-foreground">No payroll records found.</p>
        <Button asChild className="mt-4">
          <Link href="/payroll/create">Add First Payroll</Link>
        </Button>
      </Card>
    )
  }

  return (
    <>
      <Card className="overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Employee</TableHead>
              <TableHead>Period</TableHead>
              <TableHead className="text-right">Days</TableHead>
              <TableHead className="text-right">Basic Salary</TableHead>
              <TableHead className="text-right">Net Payable</TableHead>
              <TableHead className="text-center">Status</TableHead>
              <TableHead className="text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {payrolls.map((p) => (
              <TableRow key={p.id}>
                <TableCell className="font-medium">{p.employeeName}</TableCell>
                <TableCell>{monthNames[p.month - 1]} {p.year}</TableCell>
                <TableCell className="text-right tabular-nums">
                  {p.daysWorked}/{p.workingDays}
                </TableCell>
                <TableCell className="text-right tabular-nums">
                  {formatCurrency(p.basicSalary)}
                </TableCell>
                <TableCell className="text-right font-medium tabular-nums">
                  {formatCurrency(p.netPayable)}
                </TableCell>
                <TableCell className="text-center">
                  {getStatusBadge(p.status)}
                </TableCell>
                <TableCell className="text-right">
                  <div className="flex items-center justify-end gap-1">
                    {p.status === "DRAFT" && (
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => handleProcess(p.id, "APPROVED")}
                      >
                        Approve
                      </Button>
                    )}
                    {p.status === "APPROVED" && (
                      <Button
                        variant="default"
                        size="sm"
                        onClick={() => handleProcess(p.id, "PAID")}
                      >
                        Mark Paid
                      </Button>
                    )}
                    <Button asChild variant="ghost" size="sm">
                      <Link href={`/payroll/edit/${p.id}`}>Edit</Link>
                    </Button>
                    {p.status !== "PAID" && (
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-destructive hover:text-destructive"
                        onClick={() => setDeleteId(p.id)}
                      >
                        Delete
                      </Button>
                    )}
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </Card>

      <Dialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Confirm Delete</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete this payroll record? This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="secondary" onClick={() => setDeleteId(null)}>
              Cancel
            </Button>
            <Button variant="destructive" onClick={handleDelete} disabled={loading}>
              {loading ? "Deleting..." : "Delete"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}