import { Link, createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { PageHeader } from "@/components/archive-ui";
import { seedLibrary } from "@/lib/archive/catalog";
import { useArchiveStore } from "@/lib/archive/store";
import type { SubmissionStatus } from "@/lib/archive/types";

export const Route = createFileRoute("/curator")({
  component: CuratorPage,
});

function CuratorPage() {
  const submissions = useArchiveStore((state) => state.submissions);
  const audit = useArchiveStore((state) => state.audit);
  const hydrated = useArchiveStore((state) => state.hydrated);
  const review = useArchiveStore((state) => state.review);
  const remove = useArchiveStore((state) => state.removeSubmission);
  const [notes, setNotes] = useState<Record<string, string>>({});

  const counts = {
    books: seedLibrary.works.filter((work) => work.type === "book" || work.type === "pdf").length,
    audio: seedLibrary.works.filter((work) => work.type === "audio").length,
    video: seedLibrary.works.filter((work) => work.type === "video").length,
    documents: seedLibrary.works.filter((work) => work.type === "historical_document" || work.type === "manuscript" || work.type === "letter").length,
    transcripts: seedLibrary.works.filter((work) => work.type === "transcript").length,
    verified: seedLibrary.works.filter((work) => work.verification === "verified").length,
    pending: submissions.filter((item) => item.status === "pending" || item.status === "needs_evidence").length,
    rejected: submissions.filter((item) => item.status === "rejected").length,
  };

  const act = (id: string, status: Exclude<SubmissionStatus, "pending">) => {
    const note = notes[id]?.trim() ?? "";
    if (status === "approved" && note.length < 3) {
      setNotes((current) => ({ ...current, [id]: current[id] || "Approved into tier 5. Not a primary source." }));
    }
    review(id, status, note || (status === "approved" ? "Approved into tier 5. Not a primary source." : status === "rejected" ? "Rejected." : "Please add a source, date, or copy."));
  };

  return (
    <div>
      <PageHeader
        kicker="Curator"
        title="Review before the shelf trusts it"
        lede="Foundation records are already indexed. Community material waits here. Approving it adds a tier-5 note. It never becomes a quotation from a shaykh."
      />

      <dl className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-4">
        {[
          ["Books & PDFs", counts.books],
          ["Audio", counts.audio],
          ["Video", counts.video],
          ["Documents", counts.documents],
          ["Transcripts", counts.transcripts],
          ["Verified records", counts.verified],
          ["Awaiting review", hydrated ? counts.pending : "–"],
          ["Rejected", hydrated ? counts.rejected : "–"],
        ].map(([label, value]) => (
          <div key={String(label)}>
            <dt className="text-xs tracking-[0.14em] text-brass uppercase">{label}</dt>
            <dd className="mt-1 text-3xl tabular-nums">{value}</dd>
          </div>
        ))}
      </dl>
      <p className="mt-6 max-w-2xl text-sm text-muted">
        Storage: no files are kept. This foundation stores metadata and indexed notes only. A later shelf can point the same records at private object storage, with download turned off unless a curator allows it.
      </p>

      <section className="mt-10">
        <h2 className="text-xs tracking-[0.16em] text-brass uppercase">Queue</h2>
        {!hydrated ? <p className="mt-3 text-sm text-muted">Opening the local queue…</p> : null}
        {hydrated && !submissions.length ? (
          <p className="mt-3 text-sm text-muted">
            Nothing waiting. <Link to="/submit" className="underline decoration-brass underline-offset-4">Submit a note</Link> to see the path from pending to trusted.
          </p>
        ) : null}
        <ul className="mt-4 space-y-6">
          {submissions.map((item) => (
            <li key={item.id} className="border border-ink/15 bg-paper p-4">
              <div className="flex flex-wrap items-baseline justify-between gap-2">
                <h3 className="text-xl">{item.title}</h3>
                <span className="text-xs tracking-widest text-brass uppercase">{item.status.replaceAll("_", " ")}</span>
              </div>
              <p className="mt-1 text-sm text-muted">
                {item.contributor} · {item.language} · {item.materialType}
                {item.externalLink ? ` · ${item.externalLink}` : ""}
              </p>
              <p className="mt-3 leading-relaxed">{item.description}</p>
              {item.reviewNote ? <p className="mt-2 text-sm text-muted">Note: {item.reviewNote}</p> : null}
              {item.status !== "approved" && item.status !== "rejected" ? (
                <div className="mt-4 grid gap-3">
                  <label className="grid gap-1 text-sm">
                    Review note
                    <input
                      value={notes[item.id] ?? ""}
                      onChange={(event) => setNotes((current) => ({ ...current, [item.id]: event.target.value }))}
                      className="min-h-11 border border-ink/20 bg-parchment px-3"
                    />
                  </label>
                  <div className="flex flex-wrap gap-2">
                    <button type="button" className="min-h-11 bg-brass px-3 text-sm text-paper" onClick={() => act(item.id, "approved")}>Approve</button>
                    <button type="button" className="min-h-11 border border-ink/20 px-3 text-sm" onClick={() => act(item.id, "needs_evidence")}>Ask for evidence</button>
                    <button type="button" className="min-h-11 border border-ink/20 px-3 text-sm" onClick={() => act(item.id, "rejected")}>Reject</button>
                  </div>
                </div>
              ) : (
                <button type="button" className="mt-3 min-h-11 text-sm text-muted underline decoration-brass underline-offset-4" onClick={() => remove(item.id)}>
                  Remove from this desk
                </button>
              )}
            </li>
          ))}
        </ul>
      </section>

      <section className="mt-12">
        <h2 className="text-xs tracking-[0.16em] text-brass uppercase">Audit</h2>
        <ul className="mt-3 divide-y divide-ink/10 border-y border-ink/10">
          {(hydrated ? audit : []).map((entry) => (
            <li key={entry.id} className="grid gap-1 py-3 text-sm sm:grid-cols-[9rem_7rem_1fr]">
              <span className="text-muted tabular-nums">{entry.at.slice(0, 16).replace("T", " ")}</span>
              <span>{entry.action}</span>
              <span>
                {entry.target}
                <span className="block text-muted">{entry.note}</span>
              </span>
            </li>
          ))}
        </ul>
        {hydrated && !audit.length ? <p className="mt-3 text-sm text-muted">No local actions yet.</p> : null}
      </section>
    </div>
  );
}
