"use client";

import * as React from "react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { CommissionOverride, commissionOf, LoanForm, loanSchedule, P9Card, RateVersions, TimeLogTable, type CommissionRow, type Loan, type RateVersion, type TimeLog } from "@/components/medora/hr-ops";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/toast";
import { PrintButton } from "@/components/medora/print";
import { Input } from "@/components/ui/input";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { formatDate } from "@/lib/mock-data";
import { cn } from "@/lib/utils";

const fd = (d: string) => formatDate(d);
const n2 = (n: number) => n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });

const LOGS: TimeLog[] = [
  { id: "t1", date: "28 Sep", employee: "Kevin Mutua", timeIn: "18:00", timeOut: "21:30", rate: 250, paid: true },
  { id: "t2", date: "14 Oct", employee: "Kevin Mutua", timeIn: "18:00", timeOut: "22:00", rate: 250, paid: false },
  { id: "t3", date: "16 Oct", employee: "Faith Njeri (casual)", timeIn: "08:00", timeOut: "17:00", rate: 180, paid: false },
  { id: "t4", date: "18 Oct", employee: "Ali Hassan (night)", timeIn: "21:00", timeOut: "07:00", rate: 220, paid: false },
];

function TimeLogsDemo() {
  const [logs, setLogs] = React.useState(LOGS);
  return (
    <Example title="Overtime and casual time logs" description="Hours from time in and out; overnight shifts say so. Change Faith's time out to 07:00 the next morning to see the 16-hour check">
      <TimeLogTable label="Time logs, October 2026" logs={logs} onChange={(id, patch) => setLogs((xs) => xs.map((x) => (x.id === id ? { ...x, ...patch } : x)))} />
    </Example>
  );
}

const LOANS: Loan[] = [
  { ref: "LN-2026-004", kind: "Company loan", employee: "Faith Njeri", principal: 25000, instalment: 4000, firstMonth: "2026-08", repaid: 12000 },
  { ref: "HELB-7731", kind: "HELB", employee: "Grace Wanjiru", principal: 18000, instalment: 3000, firstMonth: "2026-06", repaid: 15000 },
];

function LoansDemo() {
  const [loans, setLoans] = React.useState(LOANS);
  const [issuing, setIssuing] = React.useState(false);
  const [which, setWhich] = React.useState(LOANS[0].ref);
  const [instalment, setInstalment] = React.useState(String(LOANS[0].instalment));
  const base = loans.find((l) => l.ref === which)!;
  const loan = { ...base, instalment: Number(instalment) || base.instalment };
  const rows = loanSchedule(loan);
  const outstanding = base.principal - base.repaid;
  return (
    <Example title="Loans" description="The instalment comes off every payroll until the balance is zero; the last one is smaller. Issuing one checks the employee keeps at least a third of basic pay">
      <div className="space-y-3">
        {issuing ? (
          <div className="rounded-lg border border-[var(--color-border-panel)] p-3">
            <LoanForm firstMonth="2026-11"
              employees={[
                { name: "Faith Njeri", basic: 45000, deductions: 10970 },
                { name: "Kevin Mutua", basic: 32000, deductions: 12067 },
                { name: "Grace Wanjiru", basic: 95000, deductions: 31680 },
              ]}
              onSave={(l) => {
                const ref = `LN-2026-00${5 + loans.length - 2}`;
                setLoans((xs) => [...xs, { ...l, ref, repaid: 0 }]);
                setWhich(ref);
                setInstalment(String(l.instalment));
                setIssuing(false);
                toast.add({ title: `Loan ${ref} issued`, description: `KES ${n2(l.principal)} to ${l.employee}; first deduction ${l.firstMonth}.` });
              }}
            />
          </div>
        ) : (
          <Button size="sm" variant="outline" onClick={() => setIssuing(true)}>
            Issue a loan
          </Button>
        )}
        <div className="flex flex-wrap items-end gap-3">
          <NativeSelect
            aria-label="Loan"
            value={which}
            onChange={(e) => {
              setWhich(e.target.value);
              setInstalment(String(loans.find((l) => l.ref === e.target.value)!.instalment));
            }}
          >
            {loans.map((l) => (
              <NativeSelectOption key={l.ref} value={l.ref}>
                {l.kind} · {l.employee}
              </NativeSelectOption>
            ))}
          </NativeSelect>
          <label className="flex items-center gap-2 text-sm">
            Instalment
            <Input className="h-8 w-28 tabular-nums" inputMode="numeric" value={instalment} onChange={(e) => setInstalment(e.target.value.replace(/\D/g, ""))} aria-label="Monthly instalment" />
          </label>
        </div>
        <p className="text-sm">
          <span className="font-mono">{base.ref}</span>: KES {n2(base.principal)} lent, KES {n2(base.repaid)} repaid, <span className="font-semibold">KES {n2(outstanding)} outstanding</span>. Ends {rows.at(-1)?.month} after {rows.length} deductions.
        </p>
        <div className="max-h-60 overflow-y-auto rounded-lg border border-[var(--color-border-panel)]">
          <table className="w-full border-collapse text-sm tabular-nums">
            <thead className="sticky top-0 bg-[var(--color-bg-surface-subtle)] text-left text-xs text-muted-foreground">
              <tr>
                <th scope="col" className="px-3 py-2 font-medium">
                  Payroll
                </th>
                <th scope="col" className="px-3 py-2 text-right font-medium">
                  Deduction
                </th>
                <th scope="col" className="px-3 py-2 text-right font-medium">
                  Balance after
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[var(--color-border-subtle)]">
              {rows.map((r) => (
                <tr key={r.month} className={cn(r.month === "Oct 2026" && "bg-[var(--color-bg-selected)] font-semibold")}>
                  <td className="px-3 py-1.5">{r.month}</td>
                  <td className="px-3 py-1.5 text-right">{n2(r.deduction)}</td>
                  <td className="px-3 py-1.5 text-right">{n2(r.balance)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </Example>
  );
}

const VERSIONS: RateVersion[] = [
  { id: "v3", from: "2027-02-01", nssfUpper: 108000, shifPct: 2.75, levyPct: 1.5, relief: 2400, note: "NSSF year 4 limits (example of a scheduled change)" },
  { id: "v2", from: "2025-02-01", to: "2027-01-31", nssfUpper: 72000, shifPct: 2.75, levyPct: 1.5, relief: 2400, note: "NSSF year 3 limits" },
  { id: "v1", from: "2024-10-01", to: "2025-01-31", nssfUpper: 36000, shifPct: 2.75, levyPct: 1.5, relief: 2400, note: "SHIF replaced NHIF" },
];

const COMMISSIONS: CommissionRow[] = [
  { employee: "Kevin Mutua", sales: 412300, returns: 6200, target: 300000, pct: 2 },
  { employee: "Faith Njeri", sales: 268900, returns: 1100, target: 300000, pct: 2 },
  { employee: "Grace Wanjiru", sales: 530100, returns: 0, target: 400000, pct: 1.5, override: { amount: 2500, reason: "Covered Kilimani for a week" } },
];

function RatesAndCommissionsDemo() {
  const [rows, setRows] = React.useState(COMMISSIONS);
  const [editing, setEditing] = React.useState<string | null>(null);
  return (
    <>
      <Example title="Statutory rates by effective date" description="A change by law is a new version from its date. The October 2026 payroll uses the highlighted one; earlier payslips keep theirs">
        <RateVersions versions={VERSIONS} month="2026-10" formatDate={fd} />
      </Example>
      <Example title="Commissions, October 2026" description="2% (Grace 1.5%) of own net sales above target, from Medora's sales; an override needs a reason">
        <div className="overflow-x-auto rounded-lg border border-[var(--color-border-panel)]">
          <table className="w-full border-collapse text-sm tabular-nums">
            <thead className="bg-[var(--color-bg-surface-subtle)] text-left text-xs text-muted-foreground">
              <tr>
                {["Employee", "Sales", "Returns", "Target", "Above target", "Commission"].map((h) => (
                  <th key={h} scope="col" className={cn("px-3 py-2 font-medium", h !== "Employee" && "text-right")}>
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-[var(--color-border-subtle)]">
              {rows.map((r) => {
                const above = Math.max(0, r.sales - r.returns - r.target);
                const c = commissionOf(r);
                return (
                  <tr key={r.employee}>
                    <th scope="row" className="px-3 py-2 text-left font-medium">
                      {r.employee}
                    </th>
                    <td className="px-3 py-2 text-right">{n2(r.sales)}</td>
                    <td className="px-3 py-2 text-right">{r.returns ? `−${n2(r.returns)}` : "–"}</td>
                    <td className="px-3 py-2 text-right">{n2(r.target)}</td>
                    <td className="px-3 py-2 text-right">{above ? n2(above) : <span className="text-muted-foreground">Below target</span>}</td>
                    <td className="px-3 py-2 text-right font-semibold">
                      {r.override ? (
                        <>
                          {n2(r.override.amount)}
                          <span className="block text-[11px] font-normal text-muted-foreground">
                            Worked out {n2(c)}; {r.override.reason}
                          </span>
                        </>
                      ) : (
                        n2(c)
                      )}
                      {editing !== r.employee ? (
                        <button type="button" className="block w-full cursor-pointer text-right text-xs font-normal text-primary underline-offset-2 hover:underline" onClick={() => setEditing(r.employee)}>
                          Change
                        </button>
                      ) : null}
                    </td>
                  </tr>
                );
              }).flatMap((row, i) =>
                editing === rows[i].employee
                  ? [
                      row,
                      <tr key={`${rows[i].employee}-edit`}>
                        <td colSpan={6} className="bg-muted/40 px-3 py-2">
                          <CommissionOverride
                            row={rows[i]}
                            onCancel={() => setEditing(null)}
                            onSave={(o) => {
                              setRows((xs) => xs.map((x) => (x.employee === rows[i].employee ? { ...x, override: o } : x)));
                              setEditing(null);
                            }}
                          />
                        </td>
                      </tr>,
                    ]
                  : [row],
              )}
            </tbody>
          </table>
        </div>
      </Example>
    </>
  );
}

function P9Demo() {
  const ref = React.useRef<HTMLDivElement>(null);
  const months = Array.from({ length: 12 }, (_, i) => ({ basic: i < 6 ? 30000 : 32000, allowances: 4000 }));
  return (
    <Example title="P9 tax deduction card" description="One row per month from the payroll run, the same calculation as the payslips, with year totals. A4 landscape" bare>
      <div className="flex justify-end border-b border-border px-4 py-3">
        <PrintButton target={ref} paper="a4" label="Print P9" />
      </div>
      <div className="overflow-x-auto bg-muted/50 p-6">
        <P9Card ref={ref} year={2026} employer={{ name: "Medora Pharmacy Ltd", pin: "P051924221B" }} employee={{ name: "Kevin Mutua", pin: "A009876543C", number: "EMP-004" }} months={months} />
      </div>
    </Example>
  );
}

export function HrOpsSection() {
  return (
    <Section
      id="hr-ops"
      title="Time logs, loans, statutory rates, commissions and P9"
      description="The inputs that flow into payroll. Each is worked out from its source and says how: hours from time in and out, a loan's end date from its instalment, which statutory rates a month uses, commission from own sales above target, and the year's tax from the payroll actually run."
    >
      <TimeLogsDemo />
      <div className="grid gap-4 lg:grid-cols-2">
        <LoansDemo />
        <div className="space-y-4">
          <RatesAndCommissionsDemo />
        </div>
      </div>
      <P9Demo />
    </Section>
  );
}
