import { createFileRoute } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, DateText, PageHeader } from "@/components/pbps/page";
import {
  ConfirmDialog,
  Field,
  FileDropzone,
  FormError,
  Segmented,
  TextArea,
  TextInput,
} from "@/components/pbps/form";
import { ActionButton } from "@/components/pbps/action";
import { EvidenceFile } from "@/components/pbps/file-viewer";
import { Dl, useAct, View } from "@/components/pbps/blocks";
import { DetailSkeleton, EmptyState } from "@/components/pbps/states";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { proj } from "@/api/http";
import {
  extendObligation,
  getObligation,
  reviewObligation,
  submitObligation,
} from "@/api/activities";
import type { ObligationDetail } from "@/api/types-extra";
import { useCan } from "@/lib/access";
import { todayIso } from "@/lib/dates";
import { fmtDate, fmtDateTime } from "@/lib/format";
import { P } from "@/lib/roles";

export const Route = createFileRoute("/p/$pid/obligations/$id")({ component: Page });
const REFRESH = ["obligations", "activity-review", "compliance", "dashboard"];
function Page() {
  const { id } = Route.useParams();
  const q = useQuery({ queryKey: ["obligations", id], queryFn: () => getObligation(id) });
  return (
    <View q={q} skeleton={<DetailSkeleton />}>
      {(d) => <Detail d={d} />}
    </View>
  );
}
function Detail({ d }: { d: ObligationDetail }) {
  const canSubmit = useCan(P.activitySubmit);
  const canReview = useCan(P.activityReview);
  const [ext, setExt] = useState(false);
  const today = todayIso();
  const pending = d.submissions.find((s) => s.status === "submitted");
  const open = ["open", "overdue", "returned", "upcoming", "waived"].includes(d.status);
  const configure = useCan(P.activityConfigure);
  const ev = d.activity.evidence;
  const label = new Map(ev.checklist.map((c) => [c.key, c.label]));
  return (
    <>
      <PageHeader
        title={d.activity.name}
        description={`${d.providerName} · ${d.scopeLabel}`}
        actions={
          <>
            <StatusBadge size="md" status={d.status} />
            {canReview && d.status !== "approved" && (
              <Button variant="outline" onClick={() => setExt(true)}>
                Extend window
              </Button>
            )}
          </>
        }
      />
      <div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_320px]">
        <div className="space-y-5">
          {canReview && pending && <Review key={pending.id} d={d} />}
          {canSubmit &&
            open &&
            (today < d.openDate ? (
              <Card>
                <p>
                  This obligation opens on <DateText value={d.openDate} />.
                </p>
              </Card>
            ) : today > d.closeDate && !["returned", "waived"].includes(d.status) ? (
              <Card>
                <p>
                  The submission window closed on <DateText value={d.closeDate} />. Ask M&amp;E to
                  extend it.
                </p>
              </Card>
            ) : (
              <Submit d={d} late={today > d.dueDate} />
            ))}
          <Card title="Submissions">
            {d.submissions.length === 0 ? (
              <EmptyState
                title="Nothing submitted yet"
                text="Submitted versions and review comments are kept here."
              />
            ) : (
              <ol className="space-y-5">
                {d.submissions.map((s) => (
                  <li key={s.id}>
                    <div className="flex flex-wrap items-center gap-2">
                      <b>Version {s.version}</b>
                      <StatusBadge status={s.status} />
                      {s.isLate && <StatusBadge status="overdue" label="Late" />}
                      <span className="text-[12.5px] text-muted-foreground">
                        {s.submittedBy}, {fmtDateTime(s.submittedAt)}
                      </span>
                    </div>
                    <div className="mt-2 flex flex-wrap gap-2">
                      {s.files.map((f) => (
                        <EvidenceFile
                          key={f.id}
                          name={f.name}
                          path={proj(`/obligations/${d.id}/files/${f.id}`)}
                        />
                      ))}
                    </div>
                    {s.note && <p className="mt-2 text-[13px]">{s.note}</p>}
                    {s.review && (
                      <div className="mt-2 rounded-lg bg-surface-2 p-3 text-[13px]">
                        <p className="text-muted-foreground">
                          Reviewed by {s.review.decidedBy}, {fmtDateTime(s.review.decidedAt)}
                        </p>
                        {s.review.note && <p className="mt-1">{s.review.note}</p>}
                        <ul className="mt-1">
                          {Object.entries(s.review.items).map(([k, r]) => (
                            <li key={k}>
                              <span className={r.ok ? "text-success" : "text-danger"}>
                                {r.ok ? "OK" : "Not OK"}
                              </span>
                              : {label.get(k) ?? k}
                              {r.comment && `. ${r.comment}`}
                            </li>
                          ))}
                        </ul>
                      </div>
                    )}
                  </li>
                ))}
              </ol>
            )}
          </Card>
        </div>
        <Card title="Requirements" className="h-fit">
          <Dl
            cols={1}
            items={[
              ["Opens", <DateText key="o" value={d.openDate} />],
              ["Due", <DateText key="d" value={d.dueDate} />],
              ["Closes (late accepted until)", <DateText key="c" value={d.closeDate} />],
              ["File types", ev.types.length ? ev.types.join(", ") : "Any"],
              [
                "Required items",
                <ul key="r" className="list-disc pl-4">
                  {ev.checklist.map((c) => (
                    <li key={c.key}>{c.label}</li>
                  ))}
                </ul>,
              ],
            ]}
          />
        </Card>
      </div>
      {ext && <Extend d={d} onClose={() => setExt(false)} />}
    </>
  );
}
function Submit({ d, late }: { d: ObligationDetail; late: boolean }) {
  const ev = d.activity.evidence;
  const [files, setFiles] = useState<File[]>([]);
  const [chk, setChk] = useState<Record<string, boolean>>({});
  const [note, setNote] = useState("");
  const missing = ev.checklist.filter((c) => !chk[c.key]);
  const m = useAct(
    (_: void) => submitObligation(d.id, { files, checklist: chk, ...(note ? { note } : {}) }),
    { success: "Evidence submitted", refresh: REFRESH, onError: () => {} },
  );
  return (
    <Card title={d.submissions.length ? "Submit a new version" : "Submit evidence"}>
      <FormError error={m.error} />
      {late && (
        <p className="mb-3 rounded-lg bg-warning-soft p-3 text-[13px]">
          The due date has passed. This will be marked late.
        </p>
      )}
      <FileDropzone
        multiple
        accept={ev.types}
        maxSizeMb={100}
        maxFiles={25}
        files={files}
        onFiles={setFiles}
      />
      <fieldset className="my-4">
        <legend className="text-[13px] font-medium">The files contain</legend>
        {ev.checklist.map((c) => (
          <label key={c.key} className="flex min-h-9 items-center gap-2 text-[13px]">
            <input
              type="checkbox"
              className="h-4 w-4 accent-(--primary)"
              checked={!!chk[c.key]}
              onChange={(e) => setChk((s) => ({ ...s, [c.key]: e.target.checked }))}
            />
            {c.label}
          </label>
        ))}
      </fieldset>
      <Field label="Note">
        <TextArea value={note} onChange={setNote} rows={2} maxLength={1000} />
      </Field>
      <div className="mt-3 flex items-center justify-end gap-3">
        <span className="text-[13px] text-muted-foreground">
          {files.length < ev.minFiles
            ? `Attach at least ${ev.minFiles} file.`
            : missing.length
              ? `${missing.length} required items not ticked.`
              : ""}
        </span>
        <Button
          disabled={m.isPending || files.length < ev.minFiles || missing.length > 0}
          onClick={() => m.mutate()}
        >
          {m.isPending ? "Uploading…" : "Submit evidence"}
        </Button>
      </div>
    </Card>
  );
}
function Review({ d }: { d: ObligationDetail }) {
  const items = d.activity.evidence.checklist;
  const [v, setV] = useState<Record<string, { ok: boolean; comment?: string }>>({});
  const [note, setNote] = useState("");
  const [due, setDue] = useState("");
  const m = useAct(
    (decision: "approve" | "return") =>
      reviewObligation(d.id, {
        decision,
        items: v,
        ...(note ? { note } : {}),
        ...(decision === "return" && due ? { newDueDate: due } : {}),
      }),
    { success: (r) => `Evidence ${r.status}`, refresh: REFRESH },
  );
  const bad = items.filter((i) => v[i.key] && !v[i.key]!.ok);
  const all = items.every((i) => v[i.key]);
  return (
    <Card title="Review this submission">
      <ul className="space-y-3">
        {items.map((i) => (
          <li key={i.key}>
            <div className="flex flex-wrap items-center justify-between gap-2">
              <span>{i.label}</span>
              <Segmented
                value={v[i.key] ? (v[i.key]!.ok ? "ok" : "bad") : undefined}
                onChange={(x) => setV((s) => ({ ...s, [i.key]: { ...s[i.key], ok: x === "ok" } }))}
                options={[
                  ["ok", "OK"],
                  ["bad", "Not OK"],
                ]}
              />
            </div>
            {v[i.key] && !v[i.key]!.ok && (
              <TextInput
                className="mt-1"
                aria-label={`Comment: ${i.label}`}
                placeholder="What is missing or wrong?"
                value={v[i.key]!.comment ?? ""}
                onChange={(c) => setV((s) => ({ ...s, [i.key]: { ok: false, comment: c } }))}
              />
            )}
          </li>
        ))}
      </ul>
      <div className="mt-4 grid gap-3 sm:grid-cols-2">
        <Field label="Note to the provider">
          <TextInput value={note} onChange={setNote} maxLength={1000} />
        </Field>
        {bad.length > 0 && (
          <Field label="New due date">
            <Input
              type="date"
              min={todayIso()}
              value={due}
              onChange={(e) => setDue(e.target.value)}
            />
          </Field>
        )}
      </div>
      <div className="mt-4 flex items-center justify-end gap-2">
        {!all && (
          <span className="mr-auto text-[13px] text-muted-foreground">Mark every item first.</span>
        )}
        <Button
          variant="outline"
          disabled={!all || !bad.length || m.isPending}
          onClick={() => m.mutate("return")}
        >
          Return
        </Button>
        <Button
          disabled={!all || bad.length > 0 || m.isPending}
          onClick={() => m.mutate("approve")}
        >
          Approve
        </Button>
      </div>
    </Card>
  );
}
function Extend({ d, onClose }: { d: ObligationDetail; onClose: () => void }) {
  const [date, setDate] = useState("");
  const [note, setNote] = useState("");
  const m = useAct((_: void) => extendObligation(d.id, date, note), {
    success: "Window extended",
    refresh: REFRESH,
    onDone: onClose,
  });
  return (
    <ConfirmDialog
      open
      onOpenChange={(o) => {
        if (!o) onClose();
      }}
      title="Extend the submission window"
      confirmLabel="Extend"
      pending={m.isPending || !date || date <= d.closeDate || !note.trim()}
      onConfirm={() => m.mutate()}
    >
      <div className="space-y-3">
        <Field label="New close date" required help={`Must be after ${fmtDate(d.closeDate)}.`}>
          <Input
            type="date"
            min={d.closeDate}
            value={date}
            onChange={(e) => setDate(e.target.value)}
          />
        </Field>
        <Field label="Reason" required>
          <TextArea value={note} onChange={setNote} rows={2} maxLength={500} />
        </Field>
      </div>
    </ConfirmDialog>
  );
}
