import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Mono, PageHeader, PhoneText, Stat } from "@/components/pbps/page";
import { Select, TextInput } from "@/components/pbps/form";
import { DataTable } from "@/components/pbps/data-table";
import { JobProgress } from "@/components/pbps/job-progress";
import { useAct } from "@/components/pbps/blocks";
import { KpiGridSkeleton } from "@/components/pbps/states";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import { startJob } from "@/api/ops";
import { downloadFile } from "@/api/http";
import { OUTCOME_EXPORTS, outcomeExportUrl } from "@/api/outcomes";
import { listProviderOptions } from "@/api/programme";
import { getTraineeSummary, listTrainees } from "@/api/trainees";
import type { Trainee } from "@/api/types";
import { Can, useAccess, useCan } from "@/lib/access";
import { fmtInt, fmtPct } from "@/lib/format";
import { useDebounce } from "@/lib/hooks";
import { P } from "@/lib/roles";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/p/$pid/trainees/")({ component: Page });
const NONE = { providerId: "", rosterStatus: "", sex: "", eligibility: "", band: "" };
function Page() {
  const { pid } = Route.useParams();
  const navigate = useNavigate();
  const { access } = useAccess();
  const pii = useCan(P.traineePii);
  const [page, setPage] = useState(1);
  const [s, setS] = useState("");
  const q = useDebounce(s);
  const [f, setF] = useState(NONE);
  const [job, setJob] = useState<string>();
  const sum = useQuery({ queryKey: ["trainees", "summary"], queryFn: getTraineeSummary });
  const provs = useQuery({
    queryKey: ["providers", "options"],
    queryFn: listProviderOptions,
    enabled: !access?.providerId,
  });
  const active = Object.fromEntries(Object.entries(f).filter(([, v]) => v));
  const filtered = !!q || Object.keys(active).length > 0;
  const clear = () => {
    setS("");
    setF(NONE);
    setPage(1);
  };
  const open = !!sum.data?.registrationOpen;
  const exp = useAct((_: void) => startJob("export", { what: "trainees", q, ...active }), {
    onDone: (r) => setJob(r.jobId),
  });
  const report = useAct((type: string) =>
    downloadFile(outcomeExportUrl(type, f.providerId, "xlsx")),
  );
  const sel = (k: keyof typeof NONE, l: string, o: [string, string][]) => (
    <div className="w-40">
      <Select
        ariaLabel={l}
        placeholder={l}
        value={f[k]}
        onChange={(v) => {
          setF((x) => ({ ...x, [k]: v }));
          setPage(1);
        }}
        options={o}
      />
    </div>
  );
  return (
    <>
      <PageHeader
        title="Trainees"
        description="Everyone registered in your scope."
        actions={
          <>
            <Can perm={P.reportExport}>
              <Button variant="outline" disabled={exp.isPending} onClick={() => exp.mutate()}>
                Export
              </Button>
              <div className="w-52">
                <Select
                  ariaLabel="Export report (uses the provider filter)"
                  placeholder="Export report…"
                  value=""
                  disabled={report.isPending}
                  onChange={(v) => v && report.mutate(v)}
                  options={OUTCOME_EXPORTS}
                />
              </div>
            </Can>
            {open && (
              <Can perm={P.traineeImport}>
                <Button variant="outline" asChild>
                  <Link to="/p/$pid/trainees/import" params={{ pid }}>
                    Import trainees
                  </Link>
                </Button>
              </Can>
            )}
            {open && (
              <Can perm={P.traineeCreate}>
                <Button asChild>
                  <Link to="/p/$pid/trainees/new" params={{ pid }}>
                    Add trainee
                  </Link>
                </Button>
              </Can>
            )}
          </>
        }
      />
      {sum.data && !open && (
        <p role="status" className="mb-4 rounded-lg bg-info-soft p-3 text-[13px]">
          Registration is closed. Trainees cannot be added or changed. M&amp;E can reopen it for a
          provider.
        </p>
      )}
      {job && (
        <div className="mb-4">
          <JobProgress key={job} jobId={job} title="Trainee export" />
        </div>
      )}
      {sum.data ? (
        <div className="mb-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          <Stat label="Registered" value={fmtInt(sum.data.active + sum.data.reserve)} />
          <Stat label="Female" value={fmtPct(sum.data.femalePct)} />
          <Stat
            label="Eligible"
            value={`${fmtInt(sum.data.eligible)} of ${fmtInt(sum.data.active + sum.data.reserve)}`}
          />
          <Stat label="Places left" value={fmtInt(sum.data.headroom)} />
        </div>
      ) : (
        <div className="mb-5">
          <KpiGridSkeleton n={4} />
        </div>
      )}
      <div className="mb-4 flex flex-wrap gap-2">
        <TextInput
          className="max-w-xs"
          aria-label="Search"
          placeholder="Name, ID or phone"
          value={s}
          onChange={(v) => {
            setS(v);
            setPage(1);
          }}
        />
        {!access?.providerId &&
          sel(
            "providerId",
            "All providers",
            (provs.data ?? []).map((p) => [p.id, p.name]),
          )}
        {sel("rosterStatus", "All statuses", [
          ["active", "Active"],
          ["reserve", "Reserve"],
        ])}
        {sel("sex", "Any sex", [
          ["female", "Female"],
          ["male", "Male"],
        ])}
        {sel("eligibility", "Any eligibility", [
          ["eligible", "Eligible"],
          ["not_eligible", "Not eligible"],
          ["unknown", "Unknown (details missing)"],
        ])}
        {sel("band", "Any attendance", [
          ["below80", "Below 80 %"],
          ["80to90", "80 to 90 %"],
          ["above90", "90 % and above"],
          ...(access?.providerId ? [] : [["at_risk", "At risk"] as [string, string]]),
        ])}
        {filtered && (
          <Button variant="ghost" onClick={clear}>
            Clear all
          </Button>
        )}
      </div>
      <DataTable<Trainee>
        queryKey={["trainees", page, q, f]}
        fetcher={() => listTrainees({ page, q, ...active })}
        page={page}
        onPage={setPage}
        rowKey={(r) => r.id}
        filtered={filtered}
        onClearFilters={clear}
        onRowClick={(r) => void navigate({ to: "/p/$pid/trainees/$id", params: { pid, id: r.id } })}
        empty={{
          title: "No trainees yet",
          text: "Import your first list or add trainees one by one.",
        }}
        columns={[
          {
            key: "name",
            header: "Trainee",
            cell: (r) => (
              <>
                <Link
                  className="font-medium hover:text-primary"
                  to="/p/$pid/trainees/$id"
                  params={{ pid, id: r.id }}
                  onClick={(e) => e.stopPropagation()}
                >
                  {r.fullName}
                </Link>
                <p>
                  <Mono>{r.code}</Mono>
                </p>
              </>
            ),
          },
          { key: "sex", header: "Sex", cell: (r) => <span className="capitalize">{r.sex}</span> },
          { key: "age", header: "Age", align: "right", cell: (r) => r.age },
          {
            key: "phone",
            header: "Phone",
            cell: (r) => <PhoneText value={r.phone} masked={!pii} />,
          },
          {
            key: "class",
            header: "Training and class",
            cell: (r) => (
              <span className="text-[12.5px]">
                {r.trainingTitle}
                <br />
                <span className="text-muted-foreground">
                  {r.siteName} · <span className="font-mono">{r.className}</span>
                </span>
              </span>
            ),
          },
          { key: "roster", header: "Roster", cell: (r) => <StatusBadge status={r.rosterStatus} /> },
          {
            key: "elig",
            header: "Eligibility",
            cell: (r) => <StatusBadge status={r.eligibility} />,
          },
          {
            key: "att",
            header: "Attendance",
            align: "right",
            cell: (r) => (
              <span className={cn((r.attendanceRate ?? 100) < 80 && "font-semibold text-danger")}>
                {fmtPct(r.attendanceRate)}
              </span>
            ),
          },
          { key: "drop", header: "Dropout", cell: (r) => <StatusBadge status={r.dropout} /> },
          { key: "comp", header: "Completion", cell: (r) => <StatusBadge status={r.completion} /> },
        ]}
      />
    </>
  );
}
