import { createFileRoute, Link } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery } from "@tanstack/react-query";
import { Suspense } from "react";
import { DevotionalCard } from "@/components/devotional/DevotionalCard";
import { getArchive } from "@/lib/api/treasure.functions";
import { LoadingState, EmptyState } from "@/components/devotional/States";
import type { Devotional } from "@/lib/devotional";
import { pageSeo, jsonLd, breadcrumb, absUrl } from "@/lib/seo";

const archiveQuery = queryOptions({
  queryKey: ["archive"],
  queryFn: () => getArchive(),
  staleTime: 60 * 60 * 1000,
});

export const Route = createFileRoute("/archive")({
  head: () => {
    const seo = pageSeo({
      title: "Daily Bible Word Archive | Bible Word of the Day",
      description:
        "Browse previous daily Bible words with Scripture passages, devotional messages, prayer prompts, and reflection questions.",
      path: "/archive",
    });
    return {
      meta: seo.meta,
      links: seo.links,
      scripts: [
        jsonLd({
          "@context": "https://schema.org",
          "@type": "CollectionPage",
          name: "Daily Bible Word Archive",
          url: absUrl("/archive"),
        }),
        breadcrumb([
          { name: "Home", path: "/" },
          { name: "Archive", path: "/archive" },
        ]),
      ],
    };
  },
  loader: ({ context }) => context.queryClient.ensureQueryData(archiveQuery),
  component: ArchivePage,
  errorComponent: () => (
    <div className="mx-auto max-w-3xl px-4 py-14">
      <EmptyState />
    </div>
  ),
});

function ArchivePage() {
  return (
    <div className="mx-auto max-w-6xl px-4 py-14 sm:px-6">
      <header className="max-w-2xl">
        <p className="text-xs font-medium uppercase tracking-[0.2em] text-[var(--gold)]">Archive</p>
        <h1 className="mt-2 font-serif text-4xl font-semibold text-primary sm:text-5xl">
          Previous Daily Bible Words
        </h1>
        <p className="mt-3 text-base text-muted-foreground">
          Catch up on recent reflections. New verses are added every day.
        </p>
      </header>
      <Suspense fallback={<div className="mt-10"><LoadingState /></div>}>
        <ArchiveList />
      </Suspense>
    </div>
  );
}

function ArchiveList() {
  const { data } = useSuspenseQuery(archiveQuery);
  const rows = data.results ?? [];
  if (rows.length === 0) {
    return (
      <div className="mt-10">
        <EmptyState />
        <p className="mt-4 text-center text-sm text-muted-foreground">
          The archive begins filling once today's Word has been read. Check back tomorrow.
        </p>
      </div>
    );
  }
  return (
    <div className="mt-10 grid gap-5 md:grid-cols-2 lg:grid-cols-3">
      {rows.map((r) => {
        const date = (r.date || "").slice(0, 10);
        const d: Devotional = {
          id: r.id,
          scripture_reference: r.scripture_reference || "Scripture",
          text: r.text || "",
          topics: Array.isArray(r.topics) ? r.topics : [],
          date: r.date,
        };
        return (
          <Link key={r.id} to="/daily-bible-word/$date" params={{ date }} className="block">
            <DevotionalCard devotional={d} compact />
          </Link>
        );
      })}
    </div>
  );
}
