import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, DateText, PageHeader, Stat } from "@/components/pbps/page";
import { ConfirmDialog, Field, Select, TextArea } from "@/components/pbps/form";
import { ActionButton } from "@/components/pbps/action";
import { DecisionBox, Tbl, useAct, View } from "@/components/pbps/blocks";
import { DetailSkeleton } from "@/components/pbps/states";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import { approveResubmission, discardReport, getReport, returnReport } from "@/api/outcomes";
import { DROPOUT_REASONS, NONCOMPLETION_REASONS, reportLabel } from "@/api/report-types";
import type { OutcomeReport } from "@/api/types-extra";
import { Can, useCan } from "@/lib/access";
import { fmtDateTime } from "@/lib/format";
import { P } from "@/lib/roles";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/p/$pid/outcome-reports/$id")({ component: Page });
const REASON = new Map<string, string>([...DROPOUT_REASONS, ...NONCOMPLETION_REASONS]);
function Page() {
  const { id } = Route.useParams();
  const q = useQuery({ queryKey: ["outcome-reports", id], queryFn: () => getReport(id) });
  return (
    <View q={q} skeleton={<DetailSkeleton />}>
      {(r) => <Detail key={r.id} r={r} />}
    </View>
  );
}
function Detail({ r }: { r: OutcomeReport }) {
  const { pid } = Route.useParams();
  const navigate = Route.useNavigate();
  const canReview = useCan(P.outcomeReview);
  const [filter, setFilter] = useState("");
  const [ret, setRet] = useState(false);
  const [reason, setReason] = useState("");
  const [cmp, setCmp] = useState("");
  const other = useQuery({
    queryKey: ["outcome-reports", cmp],
    queryFn: () => getReport(cmp),
    enabled: !!cmp,
  });
  const prev = new Map((cmp ? other.data?.lines : undefined)?.map((l) => [l.traineeId, l.value]));
  const refresh = ["outcome-reports", "outcomes", "classes", "trainees"];
  const m = useAct((_: void) => returnReport(r.id, reason), {
    success: "Report returned to the provider",
    refresh,
    onDone: () => setRet(false),
  });
  const dec = useAct(
    (v: { d: "approve" | "reject"; note: string }) => approveResubmission(r.id, v.d, v.note),
    { success: "Decision saved", refresh },
  );
  const lines = r.lines.filter(
    (l) =>
      !filter || (filter === "changed" ? prev.get(l.traineeId) !== l.value : l.value === filter),
  );
  return (
    <>
      <PageHeader
        title={`${reportLabel(r.reportType, r.stageKey)} report · ${r.classCode}`}
        description={`${r.providerCode} · ${r.trainingTitle}${r.submittedAt ? ` · submitted by ${r.submittedBy}, ${fmtDateTime(r.submittedAt)}` : ""}`}
        actions={
          <>
            <StatusBadge size="md" status={r.needsApproval ? "pending_review" : r.status} />
            {canReview && r.status === "accepted" && (
              <Button variant="outline" onClick={() => setRet(true)}>
                Return for correction
              </Button>
            )}
            {r.status === "accepted" && (
              <Can perm={P.projectManage}>
                <ActionButton
                  size="default"
                  label="Discard"
                  title="Discard this report?"
                  description="It no longer counts in any indicator. The report and its lines are kept in the history."
                  fields={[{ key: "reason", label: "Reason", type: "area", required: true }]}
                  run={(v) => discardReport(r.id, v["reason"] ?? "")}
                  success="Report discarded"
                  refresh={refresh}
                  confirmLabel="Discard"
                  destructive
                />
              </Can>
            )}
            <Can perm={P.outcomeSubmit}>
              {(r.status === "accepted" || r.status === "returned") && (
                <Button asChild>
                  <Link
                    to="/p/$pid/classes/$id/outcomes/$type"
                    params={{ pid, id: r.classId, type: r.reportType }}
                    search={r.stageKey ? { stage: r.stageKey } : {}}
                  >
                    Submit a new version
                  </Link>
                </Button>
              )}
            </Can>
          </>
        }
      />
      {r.reviewNote && (
        <p className="mb-4 rounded-lg bg-warning-soft p-3 text-[13px]">
          <b>Review note:</b> {r.reviewNote}
        </p>
      )}
      {r.reasonForChange && (
        <p className="mb-4 rounded-lg bg-surface-2 p-3 text-[13px]">
          <b>What changed:</b> {r.reasonForChange}
        </p>
      )}
      {r.needsApproval && (
        <Can perm={P.resubmitApprove}>
          <Card title="Approve this version?" className="mb-4 max-w-xl">
            <DecisionBox pending={dec.isPending} onDecide={(d, note) => dec.mutate({ d, note })} />
          </Card>
        </Can>
      )}
      <div className="mb-4 grid gap-3 sm:grid-cols-4">
        <Stat label="Version" value={r.version} />
        <Stat label="Yes" value={r.yesCount} />
        <Stat label="No" value={r.noCount} />
        <Stat label="Not applicable" value={r.naCount} />
      </div>
      <div className="mb-3 flex flex-wrap gap-2">
        <div className="w-44">
          <Select
            ariaLabel="Value"
            value={filter}
            onChange={setFilter}
            placeholder="All lines"
            options={[
              ["yes", "Yes"],
              ["no", "No"],
              ...(cmp ? [["changed", "Changed"] as [string, string]] : []),
            ]}
          />
        </div>
        {r.versions.length > 1 && (
          <>
            <div className="w-52">
              <Select
                ariaLabel="Version"
                value={r.id}
                onChange={(v) => {
                  if (v) void navigate({ params: { pid, id: v } });
                }}
                options={r.versions.map((v) => [v.id, `Version ${v.version} (${v.status})`])}
              />
            </div>
            <div className="w-52">
              <Select
                ariaLabel="Compare with"
                placeholder="Compare with…"
                value={cmp}
                onChange={setCmp}
                options={r.versions
                  .filter((v) => v.id !== r.id)
                  .map((v) => [v.id, `Version ${v.version}`])}
              />
            </div>
          </>
        )}
      </div>
      <Card padded={false}>
        <Tbl
          head={[
            "Trainee",
            "Value",
            ...(cmp ? ["Other version"] : []),
            "Date",
            "Reason",
            "Details",
          ]}
        >
          {lines.map((l) => {
            const diff = !!cmp && other.isSuccess && prev.get(l.traineeId) !== l.value;
            return (
              <tr key={l.traineeId} className={cn(diff && "bg-amber-soft/60")}>
                <td>
                  <Link
                    className="font-medium hover:text-primary"
                    to="/p/$pid/trainees/$id"
                    params={{ pid, id: l.traineeId }}
                  >
                    {l.name}
                  </Link>{" "}
                  <span className="font-mono text-[12px] text-muted-foreground">{l.code}</span>
                </td>
                <td>
                  <StatusBadge status={l.value ?? "pending"} />
                </td>
                {cmp && <td>{prev.get(l.traineeId) ?? "—"}</td>}
                <td>{l.eventDate ? <DateText value={l.eventDate} /> : "—"}</td>
                <td>{l.reason ? (REASON.get(l.reason) ?? l.reason) : "—"}</td>
                <td className="text-[12.5px] text-muted-foreground">
                  {Object.values(l.details ?? {})
                    .filter(Boolean)
                    .join(", ")}
                </td>
              </tr>
            );
          })}
        </Tbl>
      </Card>
      <ConfirmDialog
        open={ret}
        onOpenChange={setRet}
        title="Return this report?"
        description="The provider must submit a new version. Later reports that depend on it are blocked until then."
        confirmLabel="Return report"
        pending={m.isPending || !reason.trim()}
        onConfirm={() => m.mutate()}
      >
        <Field label="Reason" required>
          <TextArea value={reason} onChange={setReason} maxLength={1000} />
        </Field>
      </ConfirmDialog>
    </>
  );
}
