import { Link } from "@tanstack/react-router";
import { EVIDENCE_LABEL, LANGUAGE_LABEL, PIPELINE, PROCESS_LABEL, TIER_LABEL, TYPE_LABEL, VERIFY_LABEL } from "@/lib/archive/labels";
import type { Library, Work } from "@/lib/archive/types";
import { personById } from "@/lib/archive/catalog";

export function PageHeader({ kicker, title, lede }: { kicker: string; title: string; lede?: string }) {
  return (
    <header className="mb-8 max-w-3xl">
      <p className="text-xs tracking-[0.18em] text-brass uppercase">{kicker}</p>
      <h1 className="mt-2 text-4xl leading-tight font-medium md:text-5xl">{title}</h1>
      {lede ? <p className="mt-4 text-lg leading-relaxed text-muted">{lede}</p> : null}
    </header>
  );
}

export function RecordRows({ works }: { works: Work[] }) {
  if (!works.length) {
    return <p className="border-y border-ink/10 py-8 text-muted">This shelf is open. Nothing entrusted to it has been ingested.</p>;
  }
  return (
    <ul className="border-y border-ink/10">
      {works.map((work) => (
        <li key={work.id} className="border-b border-ink/10 last:border-b-0">
          <Link to="/works/$workId" params={{ workId: work.id }} className="block py-4">
            <span className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
              <span className="text-xl leading-snug">{work.title}</span>
              <span className="text-xs tracking-wide text-muted uppercase">{TYPE_LABEL[work.type]}</span>
            </span>
            {work.titleAr ? (
              <span className="arabic mt-1 block text-lg" dir="rtl" lang="ar">
                {work.titleAr}
              </span>
            ) : null}
            <span className="mt-2 block text-sm text-muted">
              Record tier {work.recordTier} · {TIER_LABEL[work.subjectTier]} underneath · {PROCESS_LABEL[work.processing]}
            </span>
          </Link>
        </li>
      ))}
    </ul>
  );
}

export function MetaGrid({ rows }: { rows: { label: string; value: string }[] }) {
  return (
    <dl className="grid gap-px border border-ink/10 bg-ink/10 sm:grid-cols-2">
      {rows.filter((row) => row.value).map((row) => (
        <div key={row.label} className="bg-paper px-4 py-3">
          <dt className="text-xs tracking-[0.14em] text-brass uppercase">{row.label}</dt>
          <dd className="mt-1 text-sm leading-relaxed">{row.value}</dd>
        </div>
      ))}
    </dl>
  );
}

export function Pipeline({ status }: { status: Work["processing"] }) {
  if (status === "not_ingested") {
    return (
      <p className="text-sm text-muted">
        This file has not entered the pipeline. The intended path is upload, validate, store, extract or transcribe, clean, segment, index, then ready. None of those steps have run.
      </p>
    );
  }
  if (status === "failed") {
    return <p className="text-sm">Processing failed. The record stays out of trusted retrieval until it is run again.</p>;
  }
  return (
    <ol className="grid gap-2 sm:grid-cols-2">
      {PIPELINE.map((step) => {
        const current = step === status;
        const done = PIPELINE.indexOf(step) < PIPELINE.indexOf(status);
        return (
          <li key={step} className={`border px-3 py-2 text-sm ${current ? "border-brass" : "border-ink/10 text-muted"}`}>
            <span className="text-xs tracking-widest uppercase">{current ? "Now" : done ? "Done" : "Ahead"}</span>
            <span className="mt-1 block text-ink">{PROCESS_LABEL[step]}</span>
          </li>
        );
      })}
    </ol>
  );
}

export function workMeta(work: Work, lib: Library): { label: string; value: string }[] {
  const names = (ids: string[]) => ids.map((id) => personById(id)?.name ?? id).join(", ");
  return [
    { label: "Record authority", value: `Tier ${work.recordTier} — ${TIER_LABEL[work.recordTier]}` },
    { label: "Underlying work", value: `Tier ${work.subjectTier} — ${TIER_LABEL[work.subjectTier]}` },
    { label: "Evidence held", value: EVIDENCE_LABEL[work.evidenceKind] },
    { label: "Verification", value: VERIFY_LABEL[work.verification] },
    { label: "Language", value: LANGUAGE_LABEL[work.language] },
    { label: "Authors", value: names(work.authorIds) },
    { label: "Speakers", value: names(work.speakerIds) },
    { label: "Date", value: work.dateLabel ?? "" },
    { label: "Publication", value: work.publication ?? "" },
    { label: "Edition", value: work.edition ?? "" },
    { label: "Visibility", value: work.visibility === "view_only" ? "View only — no download" : work.visibility },
    { label: "Download", value: work.downloadable ? "Allowed" : "Not offered" },
    { label: "Reviewer", value: work.reviewer ?? "" },
    { label: "Verified", value: work.verifiedOn ?? "" },
    { label: "Page / volume", value: [work.volume, work.page].filter(Boolean).join(" · ") },
    { label: "Audio timestamp", value: work.timestamp ?? "" },
    { label: "Duration", value: work.duration ?? "" },
    { label: "Locator", value: work.locatorStatus === "verified" ? "Checked" : "Not ingested" },
  ];
}

export function representations(work: Work, lib: Library): Work[] {
  const ids = new Set<string>(work.relatedWorkIds);
  if (work.translationOf) ids.add(work.translationOf);
  if (work.transcriptOf) ids.add(work.transcriptOf);
  if (work.audioOf) ids.add(work.audioOf);
  if (work.videoOf) ids.add(work.videoOf);
  for (const other of lib.works) {
    if (other.id === work.id) continue;
    if (other.translationOf === work.id || other.transcriptOf === work.id || other.audioOf === work.id || other.videoOf === work.id) ids.add(other.id);
  }
  return [...ids].map((id) => lib.works.find((item) => item.id === id)).filter((item): item is Work => Boolean(item));
}
