import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { Card, PageHeader } from "@/components/pbps/page";
import { DecisionBox, SubNav, useAct, View } from "@/components/pbps/blocks";
import { Button } from "@/components/ui/button";
import { approveResubmission, listReports } from "@/api/outcomes";
import { reportLabel } from "@/api/report-types";
import type { OutcomeReport } from "@/api/types-extra";
import { OUTCOMES_NAV } from "@/lib/sections";

export const Route = createFileRoute("/p/$pid/outcomes/approvals")({ component: Page });
function Page() {
  const { pid } = Route.useParams();
  const q = useQuery({
    queryKey: ["outcome-reports", "approvals"],
    queryFn: () => listReports({ needsApproval: true }),
  });
  return (
    <>
      <PageHeader
        title="Resubmission approvals"
        description="New versions of reports that a verification run has already used."
      />
      <SubNav pid={pid} items={OUTCOMES_NAV} />
      <View
        q={q}
        isEmpty={(d) => !d.items.length}
        empty={{
          title: "Nothing to approve",
          text: "A resubmission appears here when its earlier version was used for verification.",
        }}
      >
        {(d) => (
          <div className="space-y-3">
            {d.items.map((r) => (
              <Item key={r.id} r={r} />
            ))}
          </div>
        )}
      </View>
    </>
  );
}
function Item({ r }: { r: OutcomeReport }) {
  const { pid } = Route.useParams();
  const m = useAct(
    (v: { d: "approve" | "reject"; note: string }) => approveResubmission(r.id, v.d, v.note),
    { success: "Decision saved", refresh: ["outcome-reports", "outcomes", "trainees"] },
  );
  return (
    <Card
      title={`${reportLabel(r.reportType, r.stageKey)} · ${r.providerCode} · ${r.classCode} · version ${r.version}`}
      actions={
        <Button size="sm" variant="outline" asChild>
          <Link to="/p/$pid/outcome-reports/$id" params={{ pid, id: r.id }}>
            Review lines
          </Link>
        </Button>
      }
    >
      <div className="grid gap-4 md:grid-cols-[minmax(0,1fr)_300px]">
        <div>
          <p>{r.reasonForChange}</p>
          <p className="mt-2 text-[13px] text-muted-foreground">
            {r.yesCount} Yes, {r.noCount} No. A verification run has sampled this class.
          </p>
        </div>
        <DecisionBox pending={m.isPending} onDecide={(d, note) => m.mutate({ d, note })} />
      </div>
    </Card>
  );
}
