import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Lock } from "lucide-react";
import { Card, PageHeader, Stat } from "@/components/pbps/page";
import { Segmented, TextInput } from "@/components/pbps/form";
import { SubNav, View } from "@/components/pbps/blocks";
import { TableSkeleton } from "@/components/pbps/states";
import { getOutcomesBoard } from "@/api/delivery";
import { REPORT_ORDER, reportKey } from "@/api/report-types";
import type { OutcomeCell, TrainingClass } from "@/api/types";
import { useCan } from "@/lib/access";
import { fmtDate } from "@/lib/dates";
import { P } from "@/lib/roles";
import { OUTCOMES_NAV } from "@/lib/sections";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/p/$pid/outcomes/")({ component: Page });
const CELL = {
  not_due: "bg-surface-2 text-muted-foreground",
  due: "bg-warning-soft text-warning",
  overdue: "bg-danger-soft text-danger",
  accepted: "bg-success-soft text-success",
  returned: "bg-warning-soft text-warning",
  blocked: "bg-surface-2 text-muted-foreground",
};
const LBL = {
  not_due: "Not due",
  due: "Due",
  overdue: "Overdue",
  accepted: "Accepted",
  returned: "Returned",
  blocked: "Blocked",
};
function Page() {
  const { pid } = Route.useParams();
  const can = useCan(P.outcomeSubmit);
  const [s, setS] = useState("");
  const [by, setBy] = useState<"class" | "site">("class");
  const match = ({ cls }: BoardRow) =>
    `${cls.code} ${cls.providerCode} ${cls.trainingTitle} ${cls.locationName}`
      .toLowerCase()
      .includes(s.toLowerCase());
  const q = useQuery({ queryKey: ["outcomes", "board"], queryFn: getOutcomesBoard });
  return (
    <>
      <PageHeader
        title="Outcomes board"
        description="For every class: which outcome reports are due, accepted or returned."
      />
      <SubNav pid={pid} items={OUTCOMES_NAV} />
      <View
        q={q}
        skeleton={<TableSkeleton cols={9} />}
        empty={{
          title: "No classes yet",
          text: "Outcome reports become due after each class ends.",
        }}
        isEmpty={(d) => !d.rows.length}
      >
        {(d) => (
          <>
            <div className="mb-4 grid gap-3 sm:grid-cols-4">
              <Stat label="Due" value={d.summary.due} tone="warning" />
              <Stat label="Overdue" value={d.summary.overdue} tone="danger" />
              <Stat label="Returned" value={d.summary.returned} />
              <Stat label="Accepted" value={d.summary.accepted} tone="success" />
            </div>
            <div className="mb-4 flex flex-wrap items-center gap-3">
              <TextInput
                className="max-w-xs"
                aria-label="Filter classes"
                placeholder="Class, provider, training or location"
                value={s}
                onChange={setS}
              />
              <Segmented
                value={by}
                onChange={setBy}
                options={[
                  ["class", "By class"],
                  ["site", "By location"],
                ]}
              />
            </div>
            <Card padded={false}>
              <div className="overflow-x-auto">
                <table className="w-full text-[12.5px]">
                  <thead className="bg-surface-2 text-muted-foreground">
                    <tr>
                      <th scope="col" className="sticky left-0 bg-surface-2 px-4 py-2 text-left">
                        Class
                      </th>
                      {REPORT_ORDER.map((r) => (
                        <th
                          scope="col"
                          key={reportKey(r.type, r.stageKey)}
                          className="whitespace-nowrap px-2 py-2 text-left"
                        >
                          {r.label}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {by === "site" && <Sites pid={pid} rows={d.rows.filter(match)} can={can} />}
                    {by === "class" &&
                      d.rows.filter(match).map(({ cls, cells }) => (
                        <tr key={cls.id} className="border-t">
                          <td className="sticky left-0 bg-card px-4 py-2">
                            <Link
                              to="/p/$pid/classes/$id"
                              params={{ pid, id: cls.id }}
                              className="font-mono font-semibold text-primary"
                            >
                              {cls.code}
                            </Link>
                            <p className="text-[12px] text-muted-foreground">
                              {cls.providerCode} · {cls.trainingTitle}
                            </p>
                          </td>
                          {cells.map((c) => (
                            <td key={reportKey(c.type, c.stageKey)} className="px-2 py-2">
                              <OutcomeCellLink pid={pid} classId={cls.id} c={c} can={can} />
                            </td>
                          ))}
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
            </Card>
          </>
        )}
      </View>
    </>
  );
}
type BoardRow = { cls: TrainingClass; cells: OutcomeCell[] };
/** One row per training and location. A cell opens the upload for the whole location. */
function Sites({ pid, rows, can }: { pid: string; rows: BoardRow[]; can: boolean }) {
  const sites = new Map<string, BoardRow[]>();
  for (const r of rows) sites.set(r.cls.siteId, [...(sites.get(r.cls.siteId) ?? []), r]);
  return [...sites].map(([id, list]) => (
    <tr key={id} className="border-t">
      <td className="sticky left-0 bg-card px-4 py-2">
        <p className="font-semibold">
          {list[0]!.cls.locationName}, {list.length} classes
        </p>
        <p className="text-[12px] text-muted-foreground">
          {list[0]!.cls.providerCode} · {list[0]!.cls.trainingTitle}
        </p>
      </td>
      {REPORT_ORDER.map((r, i) => {
        const cells = list.map((x) => x.cells[i]!);
        const done = cells.filter((c) => c.state === "accepted").length;
        const open = cells.some((c) => ["due", "overdue", "returned"].includes(c.state));
        const state =
          done === cells.length
            ? "accepted"
            : cells.some((c) => c.state === "overdue")
              ? "overdue"
              : open
                ? "due"
                : cells.some((c) => c.state === "blocked")
                  ? "blocked"
                  : "not_due";
        const look = cn(
          "inline-flex min-h-8 items-center whitespace-nowrap rounded-md px-2 font-medium",
          CELL[state],
        );
        const text = `${done} of ${cells.length} accepted`;
        return (
          <td key={reportKey(r.type, r.stageKey)} className="px-2 py-2">
            {can && open ? (
              <Link
                className={cn(look, "hover:underline")}
                to="/p/$pid/sites/$id/outcomes/$type"
                params={{ pid, id, type: r.type }}
              >
                {text}
              </Link>
            ) : (
              <span className={look}>{text}</span>
            )}
          </td>
        );
      })}
    </tr>
  ));
}
function OutcomeCellLink({
  pid,
  classId,
  c,
  can,
}: {
  pid: string;
  classId: string;
  c: OutcomeCell;
  can: boolean;
}) {
  const title = c.reason ?? (c.dueDate ? `Due ${fmtDate(c.dueDate)}` : undefined);
  const cls = cn(
    "inline-flex min-h-8 items-center gap-1 whitespace-nowrap rounded-md px-2 font-medium",
    CELL[c.state],
  );
  const body = (
    <>
      {c.state === "blocked" && <Lock className="h-3 w-3" aria-hidden />}
      {LBL[c.state]}
      {c.state === "accepted" && ` ${c.yes}Y / ${c.no}N`}
    </>
  );
  if (c.reportId && (c.state === "accepted" || !can))
    return (
      <Link
        title={title}
        className={cn(cls, "hover:underline")}
        to="/p/$pid/outcome-reports/$id"
        params={{ pid, id: c.reportId }}
      >
        {body}
      </Link>
    );
  if (can && c.state !== "accepted")
    return (
      <Link
        title={title}
        className={cn(cls, "hover:underline")}
        to="/p/$pid/classes/$id/outcomes/$type"
        params={{ pid, id: classId, type: c.type }}
        search={c.stageKey ? { stage: c.stageKey } : {}}
      >
        {body}
      </Link>
    );
  return (
    <span title={title} className={cls}>
      {body}
    </span>
  );
}
