import { Link, createFileRoute, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { PageHeader } from "@/components/archive-ui";
import { useI18n } from "@/components/shell";
import { PROCESS_LABEL } from "@/lib/archive/labels";
import { useLiveLibrary } from "@/lib/archive/live";
import { collapseWorks, searchArchive } from "@/lib/archive/search";

export const Route = createFileRoute("/search")({
  validateSearch: (search: Record<string, unknown>) =>
    ({
      q: typeof search.q === "string" && search.q ? search.q.slice(0, 500) : undefined,
    }) as { q?: string },
  component: SearchPage,
});

function SearchPage() {
  const { q = "" } = Route.useSearch();
  const { copy } = useI18n();
  const navigate = useNavigate();
  const lib = useLiveLibrary();
  const [draft, setDraft] = useState(q);
  const hits = q ? collapseWorks(searchArchive(q, lib)) : [];

  return (
    <div>
      <PageHeader kicker="Search" title="Find a record" lede="Word search across titles, people, places, and indexed passages. It does not guess a fact the words do not touch." />
      <form
        className="flex flex-col gap-3 border-y border-ink/15 py-3 sm:flex-row"
        onSubmit={(event) => {
          event.preventDefault();
          void navigate({ to: "/search", search: { q: draft.trim() } });
        }}
      >
        <label className="sr-only" htmlFor="search-q">Search</label>
        <input id="search-q" value={draft} onChange={(event) => setDraft(event.target.value)} placeholder={copy.searchPlaceholder} className="min-h-11 w-full bg-transparent outline-none" />
        <button type="submit" className="min-h-11 bg-brass px-4 text-sm text-paper">{copy.find}</button>
      </form>
      {q ? (
        <p className="mt-4 text-sm text-muted">
          {hits.length ? `${hits.length} records` : "No record matched."}{" "}
          <Link to="/research" search={{ q }} className="underline decoration-brass underline-offset-4">
            Ask this as a research question
          </Link>
        </p>
      ) : null}
      <ul className="mt-4 border-t border-ink/10">
        {hits.map((hit) => (
          <li key={hit.work.id} className="border-b border-ink/10">
            <Link to="/works/$workId" params={{ workId: hit.work.id }} className="block py-4">
              <span className="text-xl">{hit.work.title}</span>
              <span className="mt-1 block text-sm text-muted">
                {hit.citable ? "Citable passage" : "Not evidence"} · {PROCESS_LABEL[hit.work.processing]}
              </span>
              {hit.chunk ? <span className="mt-2 block text-sm leading-relaxed">{hit.chunk.text.slice(0, 220)}{hit.chunk.text.length > 220 ? "…" : ""}</span> : null}
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
}
