import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, PageHeader, PhoneText } from "@/components/pbps/page";
import { Field, FileDropzone, Segmented, TextInput } from "@/components/pbps/form";
import { EvidenceFile } from "@/components/pbps/file-viewer";
import { Dl, useAct, View } from "@/components/pbps/blocks";
import { DetailSkeleton } from "@/components/pbps/states";
import { Button } from "@/components/ui/button";
import {
  addSubjectEvidence,
  EVIDENCE_TYPES,
  deriveStatus,
  getSubject,
  markUnreachable,
  saveResponse,
  subjectEvidencePath,
} from "@/api/verification";
import type { VerificationSubject } from "@/api/types-extra";
import { fmtDateTime } from "@/lib/format";
import { useUnsavedChangesPrompt } from "@/lib/hooks";
import { CLOSING, CODES, INTRO, OUTCOMES, QUESTIONS } from "@/lib/questionnaire";

export const Route = createFileRoute("/p/$pid/verification/call/$id")({ component: Page });
function Page() {
  const { id } = Route.useParams();
  const q = useQuery({
    queryKey: ["verification", "subject", id],
    queryFn: () => getSubject(id),
    refetchOnWindowFocus: false,
  });
  return (
    <View q={q} skeleton={<DetailSkeleton />}>
      {(s) => <Call key={s.id} s={s} />}
    </View>
  );
}
function Call({ s }: { s: VerificationSubject }) {
  const { pid, id } = Route.useParams();
  const navigate = useNavigate();
  const [note, setNote] = useState("");
  const [a, setA] = useState<Record<string, string>>(s.answers ?? {});
  const [show, setShow] = useState(false);
  const back = () =>
    void navigate({ to: "/p/$pid/verification/my-work", params: { pid }, ignoreBlocker: true });
  const att = useAct((_: void) => markUnreachable(id, note || undefined), {
    success: "Recorded as unreachable",
    refresh: ["verification"],
    onDone: back,
  });
  const shown = QUESTIONS.filter((x) => !x.when || x.when(a));
  const extra = (k: string) => a[k] === "not_correct" || (a[k] ?? "").split(",").includes("other");
  const answers = Object.fromEntries(
    shown
      .filter((x) => a[x.key])
      .flatMap((x) => [
        [x.key, a[x.key]!],
        ...(a[`${x.key}_actual`] && extra(x.key)
          ? [[`${x.key}_actual`, a[`${x.key}_actual`]!]]
          : []),
      ]),
  );
  const open = shown.filter((x) => !a[x.key]);
  const st = deriveStatus(answers);
  useUnsavedChangesPrompt(JSON.stringify(a) !== JSON.stringify(s.answers ?? {}));
  const save = useAct((_: void) => saveResponse(id, answers), {
    success: "Answers submitted for review",
    refresh: ["verification"],
    onDone: back,
  });
  return (
    <div className="mx-auto max-w-2xl space-y-4">
      <PageHeader
        title={s.name}
        description={`${s.indicatorName} · ${s.key}`}
        actions={
          <Button variant="outline" asChild>
            <Link to="/p/$pid/verification/my-work" params={{ pid }}>
              My work
            </Link>
          </Button>
        }
      />
      <Card>
        <Dl
          cols={2}
          items={[
            ["Phone", <PhoneText key="p" value={s.phone} />],
            ["Alternative phone", s.phoneAlt ? <PhoneText key="a" value={s.phoneAlt} /> : "—"],
            ["Provider", s.providerName],
            ["Training", s.trainingTitle],
            ["City", s.location],
            [
              "Sex",
              <span key="s" className="capitalize">
                {s.sex}
              </span>,
            ],
          ]}
        />
      </Card>
      <Card title="Could not reach this person?">
        <p className="mb-3 text-[13px] text-muted-foreground">
          The team calls up to three times. If nobody answered, record it here once. Otherwise fill
          in the questionnaire.
        </p>
        <Field label="Note">
          <TextInput value={note} onChange={setNote} />
        </Field>
        <Button
          className="mt-3"
          variant="outline"
          disabled={att.isPending}
          onClick={() => att.mutate()}
        >
          Mark as unreachable
        </Button>
        {s.attempts.length > 0 && (
          <ol className="mt-3 space-y-1 text-[13px]">
            {s.attempts.map((x) => (
              <li key={x.no}>
                {fmtDateTime(x.at)}: {OUTCOMES.find(([k]) => k === x.outcome)?.[1] ?? x.outcome}
                {x.note && ` (${x.note})`}
              </li>
            ))}
          </ol>
        )}
      </Card>
      <Evidence s={s} />
      <Card title="Questionnaire">
        <p className="mb-5 rounded-lg bg-surface-2 p-3">{INTRO}</p>
        <div className="space-y-5">
          {shown.map((x) => (
            <div key={x.key}>
              <Field
                label={
                  <>
                    {x.key.toUpperCase()}. {x.text}
                  </>
                }
                required
                error={show && !a[x.key] ? "Choose an answer." : undefined}
              >
                {x.multiple ? (
                  <div className="flex flex-wrap gap-2">
                    {x.options.map(([k, l]) => {
                      const list = (a[x.key] ?? "").split(",").filter(Boolean);
                      const on = list.includes(k);
                      return (
                        <Button
                          key={k}
                          type="button"
                          size="sm"
                          aria-pressed={on}
                          variant={on ? "default" : "outline"}
                          onClick={() =>
                            setA((y) => ({
                              ...y,
                              [x.key]: (on ? list.filter((z) => z !== k) : [...list, k]).join(","),
                            }))
                          }
                        >
                          {l}
                        </Button>
                      );
                    })}
                  </div>
                ) : (
                  <Segmented
                    value={a[x.key]}
                    onChange={(v) => setA((y) => ({ ...y, [x.key]: v }))}
                    options={x.options}
                  />
                )}
              </Field>
              {extra(x.key) && (
                <TextInput
                  className="mt-2"
                  aria-label={`Actual value for ${x.key}`}
                  placeholder={a[x.key] === "not_correct" ? "Record the actual value" : "Specify"}
                  value={a[`${x.key}_actual`] ?? ""}
                  onChange={(v) => setA((y) => ({ ...y, [`${x.key}_actual`]: v }))}
                />
              )}
            </div>
          ))}
        </div>
        {st && !open.length && <p className="mt-5 rounded-lg bg-surface-2 p-3">{CLOSING}</p>}
        <div className="mt-5 flex flex-wrap items-center justify-between gap-3 border-t pt-4">
          <span aria-live="polite">
            {st ? (
              <>
                Result: <b className="font-mono">{st}</b> {CODES[st]}
              </>
            ) : (
              <span className="text-muted-foreground">
                The result appears when consent and completion are answered.
              </span>
            )}
          </span>
          <Button
            size="lg"
            disabled={save.isPending}
            onClick={() => {
              setShow(true);
              if (!open.length && st) save.mutate();
            }}
          >
            {save.isPending ? "Submitting…" : "Submit answers"}
          </Button>
        </div>
      </Card>
    </div>
  );
}
function Evidence({ s }: { s: VerificationSubject }) {
  const [files, setFiles] = useState<File[]>([]);
  const [type, setType] = useState("document");
  const m = useAct((f: File[]) => addSubjectEvidence(s.id, type, f), {
    success: "Evidence added",
    refresh: ["verification"],
    onDone: () => setFiles([]),
  });
  return (
    <Card title="Evidence">
      <div className="mb-3 flex flex-wrap gap-2">
        {s.evidence.map((e) => (
          <EvidenceFile
            key={e.id}
            name={
              EVIDENCE_TYPES[e.type ?? ""] ? `${EVIDENCE_TYPES[e.type ?? ""]}: ${e.name}` : e.name
            }
            path={subjectEvidencePath(s.id, e.id)}
          />
        ))}
      </div>
      <label className="mb-3 block text-[13px]">
        Kind of evidence
        <select
          value={type}
          onChange={(e) => setType(e.target.value)}
          className="mt-1 block h-9 w-full rounded-md border bg-card px-2"
        >
          {Object.entries(EVIDENCE_TYPES).map(([k, v]) => (
            <option key={k} value={k}>
              {v}
            </option>
          ))}
        </select>
      </label>
      <FileDropzone
        multiple
        accept={[]}
        maxSizeMb={100}
        maxFiles={10}
        files={files}
        onFiles={setFiles}
      />
      <Button
        className="mt-3"
        variant="outline"
        disabled={!files[0] || m.isPending}
        onClick={() => files[0] && m.mutate(files)}
      >
        {m.isPending ? "Uploading…" : "Add evidence"}
      </Button>
    </Card>
  );
}
