import { createFileRoute } 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 { EvidenceFile } from "@/components/pbps/file-viewer";
import { reviewQueue, reviewSubject, subjectEvidencePath } from "@/api/verification";
import type { VerificationSubject } from "@/api/types-extra";
import { Can } from "@/lib/access";
import { fmtDateTime } from "@/lib/format";
import { CODES, OUTCOMES, QUESTIONS } from "@/lib/questionnaire";
import { P } from "@/lib/roles";
import { VERIFICATION_NAV } from "@/lib/sections";

export const Route = createFileRoute("/p/$pid/verification/review")({ component: Page });
function Page() {
  const { pid } = Route.useParams();
  const q = useQuery({ queryKey: ["verification", "review"], queryFn: reviewQueue });
  return (
    <>
      <PageHeader
        title="Review queue"
        description="Completed interviews waiting for a supervisor."
      />
      <SubNav pid={pid} items={VERIFICATION_NAV} />
      <View
        q={q}
        empty={{
          title: "Nothing to review",
          text: "Interviews appear here when enumerators submit them.",
        }}
      >
        {(d) => (
          <>
            <p className="mb-3 text-[13px] text-muted-foreground">
              {d.length} waiting{d.length > 30 && ", showing the first 30"}
            </p>
            <div className="space-y-3">
              {d.slice(0, 30).map((s) => (
                <Item key={s.id} s={s} />
              ))}
            </div>
          </>
        )}
      </View>
    </>
  );
}
function Item({ s }: { s: VerificationSubject }) {
  const m = useAct(
    (v: { d: "approve" | "reject"; note: string }) => reviewSubject(s.id, v.d, v.note),
    {
      success: (r) => (r.supervisor === "approved" ? "Approved" : "Sent back to the enumerator"),
      refresh: ["verification"],
    },
  );
  const a = s.answers ?? {};
  return (
    <Card
      title={s.name}
      actions={
        <span>
          <b className="font-mono">{s.status}</b> {s.status && CODES[s.status]}
        </span>
      }
    >
      <div className="grid gap-4 md:grid-cols-[minmax(0,1fr)_300px]">
        <div className="text-[13px]">
          <p className="text-muted-foreground">
            {s.key} · {s.indicatorName} · {s.providerName} · {s.enumerator ?? "not assigned"}
          </p>
          <dl className="mt-2 space-y-1">
            {QUESTIONS.filter((x) => a[x.key]).map((x) => (
              <div key={x.key}>
                <dt className="inline text-muted-foreground">{x.text} </dt>
                <dd className="inline font-medium">
                  {x.options.find(([k]) => k === a[x.key])?.[1]}
                  {a[`${x.key}_actual`] && ` (${a[`${x.key}_actual`]})`}
                </dd>
              </div>
            ))}
          </dl>
          <ol className="mt-2 text-muted-foreground">
            {s.attempts.map((x) => (
              <li key={x.no}>
                Attempt {x.no}, {fmtDateTime(x.at)}:{" "}
                {OUTCOMES.find(([k]) => k === x.outcome)?.[1] ?? x.outcome}
                {x.note && ` (${x.note})`}
              </li>
            ))}
          </ol>
          {s.evidence.length > 0 && (
            <div className="mt-3 flex flex-wrap gap-2">
              {s.evidence.map((e) => (
                <EvidenceFile key={e.id} name={e.name} path={subjectEvidencePath(s.id, e.id)} />
              ))}
            </div>
          )}
        </div>
        <Can perm={P.verApprove}>
          <DecisionBox
            pending={m.isPending}
            reject="Send back"
            onDecide={(d, note) => m.mutate({ d, note })}
          />
        </Can>
      </div>
    </Card>
  );
}
