import { createFileRoute, Link } from "@tanstack/react-router";
import { ExportMenu } from "@/components/pbps/export-menu";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, PageHeader, Stat } from "@/components/pbps/page";
import { Select } from "@/components/pbps/form";
import { SubNav, Tbl, View } from "@/components/pbps/blocks";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import { getDropoutMonitoring } from "@/api/attendance";
import { listProviderOptions } from "@/api/programme";
import { useAccess } from "@/lib/access";
import { fmtInt, fmtPct } from "@/lib/format";
import { ATTENDANCE_NAV } from "@/lib/sections";

export const Route = createFileRoute("/p/$pid/attendance/dropouts")({ component: Page });
const SIZE = 50;
function Page() {
  const { pid } = Route.useParams();
  const { access } = useAccess();
  const [flag, setFlag] = useState("");
  const [providerId, setProvider] = useState("");
  const [page, setPage] = useState(1);
  const provs = useQuery({
    queryKey: ["providers", "options"],
    queryFn: listProviderOptions,
    enabled: !access?.providerId,
  });
  const q = useQuery({
    queryKey: ["dropouts", flag, providerId],
    queryFn: () =>
      getDropoutMonitoring({ ...(flag ? { flag } : {}), ...(providerId ? { providerId } : {}) }),
  });
  return (
    <>
      <PageHeader
        title="Dropout monitoring"
        description="Trainees who can no longer reach 80 %, and dropouts the provider has not reported."
        actions={
          <ExportMenu
            report="dropout_monitoring"
            formats={["xlsx", "csv", "pdf"]}
            params={{ providerId }}
            perm="outcome.view"
          />
        }
      />
      <SubNav pid={pid} items={ATTENDANCE_NAV} />
      <div className="mb-4 flex flex-wrap gap-2">
        <div className="w-56">
          <Select
            ariaLabel="Flag"
            value={flag}
            onChange={(v) => {
              setFlag(v);
              setPage(1);
            }}
            placeholder="All flags"
            options={[
              ["atRisk", "At risk"],
              ["systemFinal", "Below 80 % at class end"],
              ["tpReported", "Reported by provider"],
              ["missingInReport", "Missing in the report"],
            ]}
          />
        </div>
        {!access?.providerId && (
          <div className="w-56">
            <Select
              ariaLabel="Provider"
              value={providerId}
              onChange={(v) => {
                setProvider(v);
                setPage(1);
              }}
              placeholder="All providers"
              options={(provs.data ?? []).map((p) => [p.id, p.name])}
            />
          </div>
        )}
      </div>
      <View q={q}>
        {(d) => (
          <div className="space-y-5">
            <div className="grid gap-3 sm:grid-cols-3 lg:grid-cols-5">
              <Stat label="At risk" value={d.summary.atRisk} tone="warning" />
              <Stat label="Below 80 % at class end" value={d.summary.systemFinal} />
              <Stat label="Reported by provider" value={d.summary.tpReported} />
              <Stat
                label="Missing in the report"
                value={d.summary.missingInReport}
                tone={d.summary.missingInReport ? "danger" : undefined}
              />
              <Stat
                label={`Effective rate (target ≤ ${fmtPct(d.summary.target)})`}
                value={fmtPct(d.summary.effectiveRate)}
              />
            </div>
            <p className="text-[13px] text-muted-foreground">
              Over-enrolment buffer:{" "}
              {d.summary.buffers
                .map((b) => `${b.providerCode} absorbs ${fmtInt(b.absorbed)}`)
                .join(" · ")}
            </p>
            {d.reasons.length > 0 && (
              <Card title="Reported reasons">
                <ul className="space-y-2">
                  {[...d.reasons]
                    .sort((a, b) => b.count - a.count)
                    .map((r) => (
                      <li
                        key={r.reason}
                        className="grid grid-cols-[180px_1fr_40px] items-center gap-3 text-[13px]"
                      >
                        <span>{r.reason}</span>
                        <span className="h-2 rounded bg-surface-2">
                          <span
                            className="block h-full rounded bg-primary"
                            style={{
                              width: `${(r.count / Math.max(...d.reasons.map((x) => x.count))) * 100}%`,
                            }}
                          />
                        </span>
                        <b className="text-right tabular">{r.count}</b>
                      </li>
                    ))}
                </ul>
              </Card>
            )}
            <Card padded={false}>
              <Tbl
                head={[
                  "Trainee",
                  "Class",
                  ">To date",
                  ">Max reachable",
                  ">Final",
                  "Flags",
                  "Reason",
                ]}
              >
                {d.rows.slice((page - 1) * SIZE, page * SIZE).map((r, i) =>
                  r.hidden ? (
                    <tr key={`h${i}`}>
                      <td colSpan={7}>
                        <span className="flex items-center gap-3">
                          <span aria-hidden className="select-none blur-sm">
                            Trainee name hidden · PBPS-000000 · 00 %
                          </span>
                          <span className="text-[12.5px] text-muted-foreground">
                            {r.providerCode} · <span className="font-mono">{r.classCode}</span> · At
                            risk. The name is shown when the class ends.
                          </span>
                        </span>
                      </td>
                    </tr>
                  ) : (
                    <tr key={r.traineeId}>
                      <td>
                        <Link
                          className="font-medium hover:text-primary"
                          to="/p/$pid/trainees/$id"
                          params={{ pid, id: r.traineeId }}
                        >
                          {r.name}
                        </Link>
                        <p className="font-mono text-[12px] text-muted-foreground">{r.code}</p>
                      </td>
                      <td>
                        {r.providerCode} · <span className="font-mono">{r.classCode}</span>
                      </td>
                      <td className="text-right">{fmtPct(r.rateToDate)}</td>
                      <td className="text-right">{fmtPct(r.maxReachable)}</td>
                      <td className="text-right">{fmtPct(r.rateFinal)}</td>
                      <td>
                        <span className="flex flex-wrap gap-1">
                          {r.missingInReport && (
                            <StatusBadge status="overdue" label="Missing in report" />
                          )}
                          {r.systemFinal && <StatusBadge status="not_met" label="Below 80 %" />}
                          {r.atRisk && !r.systemFinal && <StatusBadge status="at_risk" />}
                          {r.tpReported && <StatusBadge status="submitted" label="Reported" />}
                        </span>
                      </td>
                      <td>{r.reason ?? "—"}</td>
                    </tr>
                  ),
                )}
              </Tbl>
              <div className="flex items-center justify-between border-t px-4 py-2 text-[12.5px] text-muted-foreground">
                <span>{fmtInt(d.rows.length)} trainees</span>
                <span className="flex items-center gap-2">
                  <Button
                    size="sm"
                    variant="ghost"
                    disabled={page <= 1}
                    onClick={() => setPage(page - 1)}
                  >
                    Previous
                  </Button>
                  Page {page} of {Math.max(1, Math.ceil(d.rows.length / SIZE))}
                  <Button
                    size="sm"
                    variant="ghost"
                    disabled={page * SIZE >= d.rows.length}
                    onClick={() => setPage(page + 1)}
                  >
                    Next
                  </Button>
                </span>
              </div>
            </Card>
          </div>
        )}
      </View>
    </>
  );
}
