"use client";

import { useEffect, useState, use } from "react";
import Link from "next/link";
import { PageHeader, PageLoader, Badge, TableShell, fmtKes2, btnGhost } from "@/components/ui";

interface Payslip {
  id: number;
  employeeName: string;
  basicSalary: number;
  allowances: number;
  grossPay: number;
  nssf: number;
  shif: number;
  housingLevy: number;
  taxablePay: number;
  paye: number;
  totalDeductions: number;
  netPay: number;
}

interface Data {
  run: { id: number; periodLabel: string; status: string; totalGross: number; totalDeductions: number; totalNet: number; employeeCount: number };
  payslips: Payslip[];
}

export default function PayrollRunPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const [data, setData] = useState<Data | null>(null);
  const [error, setError] = useState("");

  useEffect(() => {
    fetch(`/api/payroll/${id}`)
      .then((r) => r.json())
      .then((d) => (d.error ? setError(d.error) : setData(d)));
  }, [id]);

  if (error) return <p className="rounded-lg bg-rose-50 p-4 text-sm text-rose-700">{error}</p>;
  if (!data) return <PageLoader label="Loading payslips…" />;

  return (
    <div>
      <PageHeader
        title={`Payroll — ${data.run.periodLabel}`}
        subtitle={`${data.run.employeeCount} employees`}
        action={
          <div className="flex items-center gap-3">
            <Badge value={data.run.status} />
            <Link href="/dashboard/payroll" className={btnGhost}>← Back</Link>
            <button onClick={() => window.print()} className={btnGhost}>🖨 Print</button>
          </div>
        }
      />

      <div className="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
        <div className="rounded-2xl border border-slate-200 bg-white p-4">
          <p className="text-xs font-medium uppercase text-slate-500">Total gross</p>
          <p className="mt-1 text-xl font-bold">{fmtKes2(data.run.totalGross)}</p>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-white p-4">
          <p className="text-xs font-medium uppercase text-slate-500">Statutory deductions</p>
          <p className="mt-1 text-xl font-bold text-rose-600">−{fmtKes2(data.run.totalDeductions)}</p>
        </div>
        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-4">
          <p className="text-xs font-medium uppercase text-emerald-700">Net payable</p>
          <p className="mt-1 text-xl font-bold text-emerald-700">{fmtKes2(data.run.totalNet)}</p>
        </div>
      </div>

      <TableShell head={["Employee", "Basic", "Allowances", "Gross", "NSSF", "SHIF", "Housing Levy", "Taxable", "PAYE", "Net Pay"]}>
        {data.payslips.map((p) => (
          <tr key={p.id} className="hover:bg-slate-50">
            <td className="whitespace-nowrap px-4 py-3 font-medium text-slate-900">{p.employeeName}</td>
            <td className="whitespace-nowrap px-4 py-3">{fmtKes2(p.basicSalary)}</td>
            <td className="whitespace-nowrap px-4 py-3">{fmtKes2(p.allowances)}</td>
            <td className="whitespace-nowrap px-4 py-3 font-medium">{fmtKes2(p.grossPay)}</td>
            <td className="whitespace-nowrap px-4 py-3 text-rose-600">{fmtKes2(p.nssf)}</td>
            <td className="whitespace-nowrap px-4 py-3 text-rose-600">{fmtKes2(p.shif)}</td>
            <td className="whitespace-nowrap px-4 py-3 text-rose-600">{fmtKes2(p.housingLevy)}</td>
            <td className="whitespace-nowrap px-4 py-3">{fmtKes2(p.taxablePay)}</td>
            <td className="whitespace-nowrap px-4 py-3 text-rose-600">{fmtKes2(p.paye)}</td>
            <td className="whitespace-nowrap px-4 py-3 font-semibold text-emerald-700">{fmtKes2(p.netPay)}</td>
          </tr>
        ))}
      </TableShell>
      <p className="mt-3 text-xs text-slate-400">
        PAYE computed on gross less NSSF, SHIF & AHL (all tax-deductible) with KES 2,400 monthly personal relief.
      </p>
    </div>
  );
}
