"use client";

/**
 * P9 tax deduction cards (HR-09; plan L): the design's `P9Card` from an employee's approved payslips for a year, so
 * its totals are the sum of what was paid. Printed on A4 landscape paper.
 */

import * as React from "react";
import { PrinterIcon } from "lucide-react";

import { P9Card } from "@/components/medora/hr-ops";
import { printElement } from "@/components/medora/print";
import { Button } from "@/components/ui/button";
import { Field, FieldLabel } from "@/components/ui/field";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { toast } from "@/components/ui/toast";
import { PayrollApi, type P9Data, type PayrollOptions } from "@/lib/api";

import { apiError } from "./shared";
import { Surface } from "@/components/medora/surface";
import { Loading } from "@/components/medora/loading";

export function P9View({ today }: { today: string }) {
  const thisYear = Number(today.slice(0, 4));
  const [opts, setOpts] = React.useState<PayrollOptions | null>(null);
  const [who, setWho] = React.useState("");
  const [year, setYear] = React.useState(thisYear);
  const [p9, setP9] = React.useState<P9Data | null>(null);
  const [loading, setLoading] = React.useState(false);
  const card = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    PayrollApi.options()
      .then(setOpts)
      .catch((e) => toast.add({ type: "error", title: "Couldn't load employees", description: apiError(e, "Try again.") }));
  }, []);
  React.useEffect(() => {
    setP9(null);
    if (!who) return;
    setLoading(true);
    PayrollApi.p9(Number(who), year)
      .then(setP9)
      .catch((e) => toast.add({ type: "error", title: "Couldn't load the P9", description: apiError(e, "Try again.") }))
      .finally(() => setLoading(false));
  }, [who, year]);

  if (!opts)
    return (
      <Loading what="the P9" shape="form" rows={2} />
    );

  return (
    <div className="space-y-4">
      <Surface className="flex flex-wrap items-end gap-3">
        <Field className="w-64">
          <FieldLabel htmlFor="p9-emp">Employee</FieldLabel>
          <NativeSelect id="p9-emp" value={who} onChange={(e) => setWho(e.target.value)}>
            <NativeSelectOption value="">Choose the employee</NativeSelectOption>
            {opts.employees.map((e) => (
              <NativeSelectOption key={e.id} value={String(e.id)}>
                {e.name} ({e.number})
              </NativeSelectOption>
            ))}
          </NativeSelect>
        </Field>
        <Field className="w-32">
          <FieldLabel htmlFor="p9-year">Year</FieldLabel>
          <NativeSelect id="p9-year" value={String(year)} onChange={(e) => setYear(Number(e.target.value))}>
            {[thisYear - 2, thisYear - 1, thisYear].map((y) => (
              <NativeSelectOption key={y} value={String(y)}>
                {y}
              </NativeSelectOption>
            ))}
          </NativeSelect>
        </Field>
        {p9 ? (
          <Button size="sm" variant="outline" onClick={() => card.current && printElement(card.current, "a4")}>
            <PrinterIcon data-icon="inline-start" />
            Print P9
          </Button>
        ) : null}
      </Surface>
      {loading ? <Loading what="the P9" columns={8} rows={6} numeric={[1, 2, 3, 4, 5, 6, 7]} footer /> : null}
      {p9 ? (
        <>
          <p className="text-xs text-muted-foreground">
            From {p9.payslips} approved {p9.payslips === 1 ? "payslip" : "payslips"} in {p9.year}. Check the layout against KRA&apos;s current P9A form before filing.
          </p>
          <div className="overflow-x-auto">
            <P9Card
              ref={card}
              employer={{ name: p9.employer.name, pin: p9.employer.pin || "–" }}
              employee={{ name: p9.employee.name, pin: p9.employee.pin ?? "–", number: p9.employee.number }}
              year={p9.year}
              months={[]}
              rows={p9.rows.map((r) => ({ ...r, housingLevy: r.levy }))}
              ratesAsAt="the dates of each month's confirmed rates"
            />
          </div>
        </>
      ) : null}
    </div>
  );
}
