import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { AlertTriangle, Trash2 } from "lucide-react";
import { ConfirmDialog, Field, FormError, TextArea } from "@/components/pbps/form";
import { useAct } from "@/components/pbps/blocks";
import { Button } from "@/components/ui/button";
import { deleteTrainee, getDeleteImpact } from "@/api/trainees";

/** Shows where the trainee's data is held, then removes it everywhere. */
export function DeleteTrainee({ pid, id, code }: { pid: string; id: string; code: string }) {
  const [open, setOpen] = useState(false);
  const [reason, setReason] = useState("");
  const nav = useNavigate();
  const q = useQuery({
    queryKey: ["trainees", id, "delete-impact"],
    queryFn: () => getDeleteImpact(id),
    enabled: open,
  });
  const m = useAct((_: void) => deleteTrainee(id, { reason: reason.trim(), confirmCode: code }), {
    success: `${code} deleted`,
    refresh: ["trainees", "classes", "outcomes", "verification", "attendance", "dashboard"],
    onDone: () => {
      setOpen(false);
      void nav({ to: "/p/$pid/trainees", params: { pid } });
    },
  });
  const d = q.data;
  return (
    <>
      <Button variant="outline" className="text-danger" onClick={() => setOpen(true)}>
        <Trash2 className="h-4 w-4" /> Delete
      </Button>
      <ConfirmDialog
        open={open}
        onOpenChange={setOpen}
        title={`Delete ${code}?`}
        description="This removes the trainee and every result that holds them. A full copy is kept in the audit log."
        confirmLabel="Delete everywhere"
        destructive
        typeToConfirm={code}
        pending={m.isPending}
        disabled={!d || reason.trim().length < 10}
        onConfirm={() => m.mutate()}
      >
        <FormError error={m.error ?? q.error} />
        {!d ? (
          <p className="text-muted-foreground">Looking up where this trainee appears…</p>
        ) : (
          <div className="max-h-[50vh] space-y-3 overflow-y-auto pr-1">
            {d.sampled && (
              <p className="flex gap-2 rounded-lg bg-warning-soft p-3 text-[13px] font-medium">
                <AlertTriangle className="h-4 w-4 shrink-0" /> This trainee is already in a
                verification sample.
              </p>
            )}
            {d.warnings.map((w) => (
              <p key={w} className="rounded-lg border border-warning/40 p-2.5 text-[13px]">
                {w}
              </p>
            ))}
            <div>
              <p className="mb-1 text-[13px] font-medium">Removed from</p>
              <ul className="space-y-2">
                {d.items.map((x) => (
                  <li key={x.area} className="rounded-lg border p-2.5 text-[13px]">
                    <span className="font-medium">{x.area}</span>
                    <ul className="mt-1 list-disc pl-5 text-muted-foreground">
                      {x.detail.map((s) => (
                        <li key={s}>{s}</li>
                      ))}
                    </ul>
                  </li>
                ))}
              </ul>
            </div>
            <Field label="Why is this trainee deleted?" required>
              <TextArea value={reason} onChange={setReason} rows={2} maxLength={1000} />
            </Field>
          </div>
        )}
      </ConfirmDialog>
    </>
  );
}
