import { createFileRoute, Link } from "@tanstack/react-router";
import { keepPreviousData, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Card, PageHeader, Stat } from "@/components/pbps/page";
import {
  ConfirmDialog,
  Field,
  FileDropzone,
  FormError,
  Segmented,
  Select,
  TextInput,
} from "@/components/pbps/form";
import { DownloadButton, Tbl, useAct, View } from "@/components/pbps/blocks";
import { JobProgress } from "@/components/pbps/job-progress";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import { getTraining, listTrainings } from "@/api/delivery";
import { listProviderOptions } from "@/api/programme";
import {
  commitImport,
  decideImportDuplicate,
  discardImport,
  fixImportRow,
  getImport,
  getTemplateUrl,
  listImportRows,
  listImports,
  startImport,
} from "@/api/trainees";
import type { ImportRow } from "@/api/types-extra";
import { useAccess } from "@/lib/access";
import { fmtDateTime, fmtInt } from "@/lib/format";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/p/$pid/trainees/import")({ component: Page });
function Page() {
  const [batch, setBatch] = useState<{ id: string; jobId?: string }>();
  return (
    <>
      <PageHeader
        title="Import trainees"
        description="Upload a list, fix every problem on screen, then import. Nothing is saved until you confirm."
      />
      {batch ? (
        <Review key={batch.id} {...batch} onClose={() => setBatch(undefined)} />
      ) : (
        <>
          <Upload onStart={(id, jobId) => setBatch({ id, jobId })} />
          <History onOpen={(id) => setBatch({ id })} />
        </>
      )}
    </>
  );
}
function Upload({ onStart }: { onStart: (id: string, jobId: string) => void }) {
  const { access } = useAccess();
  const fixed = access?.providerId;
  const [f, setF] = useState({
    providerId: fixed ?? "",
    trainingId: "",
    siteId: "",
    mode: "import" as "import" | "check_only",
  });
  const [files, setFiles] = useState<File[]>([]);
  const provs = useQuery({
    queryKey: ["providers", "options"],
    queryFn: listProviderOptions,
    enabled: !fixed,
  });
  const trs = useQuery({
    queryKey: ["trainings", "", "", f.providerId],
    queryFn: () => listTrainings({ providerId: f.providerId }),
    enabled: !!f.providerId,
  });
  const tr = useQuery({
    queryKey: ["trainings", f.trainingId],
    queryFn: () => getTraining(f.trainingId),
    enabled: !!f.trainingId,
  });
  const m = useAct((file: File) => startImport({ ...f, file }), {
    onError: () => {},
    onDone: (r) => onStart(r.batchId, r.jobId),
  });
  return (
    <Card title="New import" className="mb-6 max-w-3xl">
      <FormError error={m.error} />
      <div className="grid gap-4 sm:grid-cols-2">
        {!fixed && (
          <Field label="Training provider" required>
            <Select
              value={f.providerId}
              onChange={(v) => setF((s) => ({ ...s, providerId: v, trainingId: "", siteId: "" }))}
              options={(provs.data ?? []).map((p) => [p.id, `${p.code} · ${p.name}`])}
            />
          </Field>
        )}
        <Field label="Training" required>
          <Select
            value={f.trainingId}
            onChange={(v) => setF((s) => ({ ...s, trainingId: v, siteId: "" }))}
            options={(trs.data?.items ?? []).map((t) => [t.id, t.title])}
            disabled={!f.providerId}
          />
        </Field>
        <Field label="Site" required>
          <Select
            value={f.siteId}
            onChange={(v) => setF((s) => ({ ...s, siteId: v }))}
            options={(tr.data?.sites ?? []).map((s) => [s.site.id, s.site.location.name])}
            disabled={!f.trainingId}
          />
        </Field>
        <Field
          label="Mode"
          help={
            f.mode === "import"
              ? "Validate, then register the trainees."
              : "Duplicate and quality report only. Nothing can be imported."
          }
        >
          <Segmented
            value={f.mode}
            onChange={(v) => setF((s) => ({ ...s, mode: v }))}
            options={[
              ["import", "Import"],
              ["check_only", "Check only"],
            ]}
          />
        </Field>
      </div>
      <div className="my-4 flex flex-wrap gap-2">
        <DownloadButton path={getTemplateUrl("xlsx", f.trainingId || undefined)}>
          Excel template
        </DownloadButton>
        <DownloadButton path={getTemplateUrl("csv", f.trainingId || undefined)}>
          CSV template
        </DownloadButton>
      </div>
      <FileDropzone
        accept={["csv", "xlsx"]}
        maxSizeMb={10}
        files={files}
        onFiles={setFiles}
        help="CSV or XLSX, up to 5,000 rows and 10 MB"
      />
      <div className="mt-4 flex justify-end">
        <Button
          disabled={!f.siteId || !files[0] || m.isPending}
          onClick={() => files[0] && m.mutate(files[0])}
        >
          {m.isPending ? "Uploading…" : "Upload and validate"}
        </Button>
      </div>
    </Card>
  );
}
function History({ onOpen }: { onOpen: (id: string) => void }) {
  const q = useQuery({ queryKey: ["imports"], queryFn: listImports });
  return (
    <Card title="Import history" padded={false}>
      <View
        q={q}
        empty={{
          title: "No imports yet",
          text: "Uploaded files and their results are listed here.",
        }}
      >
        {(rows) => (
          <Tbl head={["File", "Target", "When", "By", ">Rows", ">Created", "Status", ""]}>
            {rows.map((b) => (
              <tr key={b.id}>
                <td className="font-medium">{b.fileName}</td>
                <td>{b.target.label}</td>
                <td>{fmtDateTime(b.createdAt)}</td>
                <td>{b.createdBy}</td>
                <td className="text-right">{b.counts.total}</td>
                <td className="text-right">{b.counts.created ?? "—"}</td>
                <td>
                  <StatusBadge status={b.status} />
                </td>
                <td>
                  <Button size="sm" variant="ghost" onClick={() => onOpen(b.id)}>
                    Open
                  </Button>
                </td>
              </tr>
            ))}
          </Tbl>
        )}
      </View>
    </Card>
  );
}
function Review({ id, jobId, onClose }: { id: string; jobId?: string; onClose: () => void }) {
  const { pid } = Route.useParams();
  const qc = useQueryClient();
  const [tab, setTab] = useState("all");
  const [page, setPage] = useState(1);
  const [commitJob, setCommitJob] = useState<string>();
  const [ask, setAsk] = useState(false);
  const reload = () => {
    void qc.invalidateQueries({ queryKey: ["import", id] });
    void qc.invalidateQueries({ queryKey: ["imports"] });
  };
  const b = useQuery({ queryKey: ["import", id], queryFn: () => getImport(id) });
  const rows = useQuery({
    queryKey: ["import", id, "rows", tab, page],
    queryFn: () => listImportRows(id, tab, page),
    enabled: !!b.data && b.data.status !== "validating",
    placeholderData: keepPreviousData,
  });
  const commit = useAct((_: void) => commitImport(id), {
    onDone: (r) => {
      setAsk(false);
      setCommitJob(r.jobId);
    },
  });
  const drop = useAct((_: void) => discardImport(id), {
    success: "Import discarded",
    refresh: ["imports"],
    onDone: onClose,
  });
  if (b.isPending || b.isError) return <View q={b}>{() => null}</View>;
  const d = b.data;
  const c = d.counts;
  const over = d.capacity ? d.capacity.registered + d.capacity.adding - d.capacity.max : 0;
  const final = d.status === "committed" || d.status === "discarded" || d.status === "committing";
  const blockers = [
    c.error ? `${c.error} rows with errors` : "",
    c.duplicate ? `${c.duplicate} possible duplicates to decide` : "",
    d.headerIssues.length ? "missing columns" : "",
    over > 0 ? `${over} rows over capacity` : "",
  ].filter(Boolean);
  return (
    <div className="space-y-5">
      {jobId && d.status === "validating" && (
        <JobProgress jobId={jobId} title="Validating" onDone={reload} />
      )}
      {commitJob && (
        <JobProgress
          jobId={commitJob}
          title="Importing"
          onDone={() => {
            reload();
            void qc.invalidateQueries({ queryKey: ["trainees"] });
            void qc.invalidateQueries({ queryKey: ["classes"] });
          }}
        />
      )}
      {d.status !== "validating" && (
        <>
          <div className="flex flex-wrap items-center gap-2">
            <b>{d.fileName}</b>
            <span className="text-muted-foreground">{d.target.label}</span>
            <StatusBadge status={d.status} />
            <Button className="ml-auto" variant="ghost" onClick={onClose}>
              All imports
            </Button>
          </div>
          <div className="grid gap-3 sm:grid-cols-3 lg:grid-cols-6">
            <Stat label="Rows" value={fmtInt(c.total)} />
            <Stat label="Valid" value={fmtInt(c.valid)} tone="success" />
            <Stat label="Errors" value={c.error} tone={c.error ? "danger" : undefined} />
            <Stat label="Warnings" value={c.warning} tone={c.warning ? "warning" : undefined} />
            <Stat
              label="Undecided duplicates"
              value={c.duplicate}
              tone={c.duplicate ? "warning" : undefined}
            />
            <Stat label="Skipped" value={c.skipped} />
          </div>
          {d.headerIssues.length > 0 && (
            <div role="alert" className="rounded-lg bg-danger-soft p-3 text-[13px] text-danger">
              <b>The header row is not valid.</b> {d.headerIssues.join(". ")}. Download the template
              and upload again.
            </div>
          )}
          {over > 0 && !final && (
            <div role="alert" className="rounded-lg bg-danger-soft p-3 text-[13px] text-danger">
              This import would bring the provider to{" "}
              {fmtInt(d.capacity!.registered + d.capacity!.adding)} of {fmtInt(d.capacity!.max)}{" "}
              allowed. Skip {over} rows.
            </div>
          )}
          {d.status === "committed" ? (
            <Card>
              <p>
                <b>{fmtInt(c.created)} trainees imported.</b> Rosters freeze 14 days after each
                class starts.
              </p>
              <Button asChild className="mt-3">
                <Link to="/p/$pid/trainees" params={{ pid }}>
                  View trainees
                </Link>
              </Button>
            </Card>
          ) : (
            <>
              <div className="flex flex-wrap gap-1">
                {[
                  ["all", "All"],
                  ["error", "Errors"],
                  ["warning", "Warnings"],
                  ["duplicate", "Duplicates"],
                  ["ok", "Valid"],
                ].map(([k, l]) => (
                  <Button
                    key={k}
                    size="sm"
                    variant={tab === k ? "default" : "outline"}
                    onClick={() => {
                      setTab(k!);
                      setPage(1);
                    }}
                  >
                    {l}
                  </Button>
                ))}
              </div>
              <Card padded={false}>
                <View
                  q={rows}
                  empty={{ title: "No rows here", text: "Choose another filter." }}
                  isEmpty={(r) => r.items.length === 0}
                >
                  {(r) => (
                    <>
                      <Tbl
                        head={[
                          "Row",
                          "",
                          ...Object.keys(r.items[0]?.values ?? {}).map((k) => k.replace(/_/g, " ")),
                        ]}
                      >
                        {r.items.map((row) => (
                          <Row
                            key={row.rowNo}
                            batchId={id}
                            row={row}
                            locked={final}
                            onChange={reload}
                          />
                        ))}
                      </Tbl>
                      <div className="flex items-center justify-between border-t px-4 py-2 text-[12.5px] text-muted-foreground">
                        <span>{fmtInt(r.total)} rows</span>
                        <span className="flex items-center gap-2">
                          <Button
                            size="sm"
                            variant="ghost"
                            disabled={page <= 1}
                            onClick={() => setPage(page - 1)}
                          >
                            Previous
                          </Button>
                          Page {page} of {Math.max(1, Math.ceil(r.total / 50))}
                          <Button
                            size="sm"
                            variant="ghost"
                            disabled={page * 50 >= r.total}
                            onClick={() => setPage(page + 1)}
                          >
                            Next
                          </Button>
                        </span>
                      </div>
                    </>
                  )}
                </View>
              </Card>
              {!final && (
                <div className="sticky bottom-0 z-10 flex flex-wrap items-center justify-end gap-3 border-t bg-background py-3">
                  <span className="mr-auto text-[13px] text-muted-foreground">
                    {d.mode === "check_only"
                      ? "Check only: nothing will be imported."
                      : blockers.length
                        ? `Before importing: ${blockers.join(", ")}.`
                        : "Ready to import."}
                  </span>
                  <Button variant="outline" disabled={drop.isPending} onClick={() => drop.mutate()}>
                    Discard
                  </Button>
                  {d.mode === "import" && (
                    <Button
                      disabled={blockers.length > 0 || !!commitJob}
                      onClick={() => setAsk(true)}
                    >
                      Import {fmtInt(c.valid)} trainees
                    </Button>
                  )}
                </div>
              )}
            </>
          )}
          <ConfirmDialog
            open={ask}
            onOpenChange={setAsk}
            title={`Import ${fmtInt(c.valid)} trainees?`}
            description={`${c.skipped} rows will be skipped. Every trainee gets an ID and counts toward the provider's limit.`}
            confirmLabel="Import"
            pending={commit.isPending}
            onConfirm={() => commit.mutate()}
          />
        </>
      )}
    </div>
  );
}
function Row({
  batchId,
  row,
  locked,
  onChange,
}: {
  batchId: string;
  row: ImportRow;
  locked: boolean;
  onChange: () => void;
}) {
  const [edit, setEdit] = useState<string>();
  const [v, setV] = useState("");
  const [reason, setReason] = useState("");
  const fix = useAct((x: Record<string, string>) => fixImportRow(batchId, row.rowNo, x), {
    onDone: () => {
      setEdit(undefined);
      onChange();
    },
  });
  const dec = useAct(
    (d: "skip" | "not_duplicate") => decideImportDuplicate(batchId, row.rowNo, d, reason),
    { onDone: onChange },
  );
  const skipped = row.decision === "skip";
  const cols = Object.keys(row.values);
  const dup = row.duplicates?.[0];
  const save = () => {
    if (fix.isPending) return;
    if (edit && v !== row.values[edit]) fix.mutate({ [edit]: v });
    else setEdit(undefined);
  };
  return (
    <>
      <tr className={cn(skipped && "text-muted-foreground line-through")}>
        <td>{row.rowNo}</td>
        <td>
          <StatusBadge
            status={
              skipped
                ? "closed"
                : row.status === "ok"
                  ? "approved"
                  : row.status === "error"
                    ? "failed"
                    : "at_risk"
            }
            label={skipped ? "Skipped" : row.status === "ok" ? "Valid" : row.status}
          />
        </td>
        {cols.map((k) => {
          const is = row.issues.find((i) => i.field === k);
          return (
            <td
              key={k}
              title={is?.message}
              className={cn(
                "!py-1",
                is && (is.severity === "error" ? "bg-danger-soft" : "bg-warning-soft"),
              )}
            >
              {edit === k ? (
                <TextInput
                  autoFocus
                  aria-label={`${k}, row ${row.rowNo}`}
                  className="min-w-32"
                  value={v}
                  onChange={setV}
                  onBlur={save}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") save();
                    if (e.key === "Escape") setEdit(undefined);
                  }}
                  disabled={fix.isPending}
                />
              ) : (
                <button
                  type="button"
                  disabled={locked || skipped}
                  className="min-h-8 w-full min-w-16 text-left"
                  onClick={() => {
                    setEdit(k);
                    setV(row.values[k] ?? "");
                  }}
                >
                  {row.values[k] || "—"}
                </button>
              )}
            </td>
          );
        })}
      </tr>
      {!skipped && !locked && (row.issues.length > 0 || (dup && !row.decisionNote)) && (
        <tr className="!border-t-0">
          <td />
          <td colSpan={cols.length + 1} className="!pt-0 text-[12.5px]">
            {row.issues.map((i, k) => (
              <p key={k} className={i.severity === "error" ? "text-danger" : "text-warning"}>
                {i.message}
              </p>
            ))}
            {dup && !row.decisionNote && (
              <div className="mt-1 flex flex-wrap items-center gap-2">
                <span>
                  Matches <b>{dup.name}</b> ({dup.code}, {dup.provider}), {dup.score} %:{" "}
                  {dup.reasons.join(", ")}.
                </span>
                <TextInput
                  className="w-56"
                  aria-label="Reason this is a different person"
                  placeholder="Why a different person?"
                  value={reason}
                  onChange={setReason}
                />
                <Button
                  size="sm"
                  variant="outline"
                  disabled={!reason.trim() || dec.isPending}
                  onClick={() => dec.mutate("not_duplicate")}
                >
                  Different person
                </Button>
              </div>
            )}
            <Button
              size="sm"
              variant="ghost"
              className="mt-1"
              disabled={dec.isPending}
              onClick={() => dec.mutate("skip")}
            >
              Skip this row
            </Button>
          </td>
        </tr>
      )}
    </>
  );
}
