import { createFileRoute, Link, redirect } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery } from "@tanstack/react-query";
import { Suspense } from "react";
import { getTopicPage, type TopicPageData } from "@/lib/api/topics-registry.functions";
import { slugToTopic, topicToSlug } from "@/lib/topics";
import { TopicDevotionalCard } from "@/components/devotional/TopicDevotionalCard";
import { EmailSignup } from "@/components/devotional/EmailSignup";
import { LoadingState, EmptyState, ErrorState } from "@/components/devotional/States";
import { pageSeo, breadcrumb, jsonLd, absUrl } from "@/lib/seo";

const topicPageQuery = (slug: string) =>
  queryOptions({
    queryKey: ["topic-page", slug],
    queryFn: () => getTopicPage({ data: { slug } }),
    staleTime: 6 * 60 * 60 * 1000,
  });

export const Route = createFileRoute("/topics/$topic")({
  beforeLoad: ({ params }) => {
    const canonical = topicToSlug(slugToTopic(params.topic));
    if (canonical && params.topic !== canonical) {
      throw redirect({ to: "/topics/$topic", params: { topic: canonical }, replace: true });
    }
  },
  head: ({ params, loaderData }) => {
    const slug = params.topic;
    const page = loaderData as TopicPageData | undefined;
    const displayName = page?.displayName ?? slugToTopic(slug);
    const indexable = page?.indexable !== false;
    const title = `Bible Devotionals About ${displayName} | Bible Word of the Day`;
    const description = `Read Bible devotionals about ${displayName} with Scripture passages, practical messages, prayer prompts, and reflection questions.`;
    const path = `/topics/${slug}`;
    const seo = pageSeo({ title, description, path, noindex: !indexable });
    return {
      meta: seo.meta,
      links: seo.links,
      scripts: [
        jsonLd({
          "@context": "https://schema.org",
          "@type": "CollectionPage",
          name: title,
          description,
          url: absUrl(path),
          about: { "@type": "Thing", name: displayName },
        }),
        breadcrumb([
          { name: "Home", path: "/" },
          { name: "Topics", path: "/topics" },
          { name: displayName, path },
        ]),
      ],
    };
  },
  loader: ({ context, params }) =>
    context.queryClient.ensureQueryData(topicPageQuery(params.topic)),
  component: TopicDetail,
  errorComponent: () => <div className="mx-auto max-w-4xl px-4 py-14"><ErrorState /></div>,
  notFoundComponent: () => <div className="mx-auto max-w-4xl px-4 py-14"><EmptyState /></div>,
});

function TopicDetail() {
  const { topic } = Route.useParams();
  return (
    <div className="mx-auto max-w-5xl px-4 py-14 sm:px-6">
      <Link to="/topics" className="text-sm text-muted-foreground hover:text-primary">← All topics</Link>
      <Suspense fallback={<LoadingState />}>
        <Results slug={topic} />
      </Suspense>
      <div className="mt-14 rounded-2xl border border-border bg-card p-8 shadow-soft">
        <EmailSignup />
      </div>
    </div>
  );
}

function Results({ slug }: { slug: string }) {
  const { data: page } = useSuspenseQuery(topicPageQuery(slug));
  const display = page.displayName;
  return (
    <>
      <h1 className="mt-3 font-serif text-4xl font-semibold text-primary sm:text-5xl">
        Bible Devotionals About {display}
      </h1>
      <p className="mt-3 max-w-2xl text-base text-muted-foreground">
        Scripture reflections to help you live God's Word on {display.toLowerCase()}. Each card includes a verse and a short, practical insight.
      </p>
      <div className="mt-10">
        {page.devotionals.length === 0 ? (
          <EmptyState
            title={page.found ? "No devotionals yet" : "Topic not found"}
            message={page.found ? "We couldn't find devotionals for this topic right now." : "This topic isn't in our library."}
          />
        ) : (
          <div className="grid gap-5 md:grid-cols-2">
            {page.devotionals.map((d, i) => (
              <TopicDevotionalCard
                key={d.id}
                devotional={{
                  id: d.id,
                  scripture_reference: d.scripture_reference || "Scripture",
                  context: d.context || undefined,
                  text: d.text,
                  topics: d.topics,
                  bookOrder: d.bookOrder ?? undefined,
                }}
                eager={i < 5}
              />
            ))}
          </div>
        )}
      </div>
    </>
  );
}
