import { createFileRoute, Link, notFound } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery, useQuery } from "@tanstack/react-query";
import { Suspense } from "react";
import { getArchive } from "@/lib/api/treasure.functions";
import { getBiblePassage } from "@/lib/api/bible.functions";
import { BiblePassageCard } from "@/components/devotional/BiblePassageCard";
import { DevotionalMessageCard } from "@/components/devotional/DevotionalMessageCard";
import { PrayerBox } from "@/components/devotional/PrayerBox";
import { ReflectionBox } from "@/components/devotional/ReflectionBox";
import { ShareButton } from "@/components/devotional/ShareButton";
import { LoadingState, EmptyState } from "@/components/devotional/States";
import { pageSeo, breadcrumb, jsonLd, SITE_LOGO, SITE_NAME, absUrl, DEFAULT_OG_IMAGE } from "@/lib/seo";

const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;

const dailyQuery = (date: string) =>
  queryOptions({
    queryKey: ["daily", date],
    queryFn: async () => {
      const all = await getArchive();
      const row = (all.results ?? []).find((r) => r.date?.slice(0, 10) === date);
      return row ?? null;
    },
    staleTime: 60 * 60 * 1000,
  });

function formatDate(d: string): string {
  const [y, m, day] = d.split("-").map(Number);
  return new Date(Date.UTC(y, m - 1, day)).toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
    timeZone: "UTC",
  });
}

export const Route = createFileRoute("/daily-bible-word/$date")({
  beforeLoad: ({ params }) => {
    if (!DATE_RE.test(params.date)) throw notFound();
  },
  loader: ({ context, params }) =>
    context.queryClient.ensureQueryData(dailyQuery(params.date)),
  head: ({ params, loaderData }) => {
    const date = params.date;
    const pretty = formatDate(date);
    const ref = loaderData?.scripture_reference || "Bible Devotional";
    const title = `Daily Bible Word for ${pretty} | ${ref}`;
    const description = `Read the Bible Word of the Day for ${pretty}, featuring ${ref}, a devotional message, prayer, and reflection.`;
    const path = `/daily-bible-word/${date}`;
    const seo = pageSeo({ title, description, path, type: "article" });
    return {
      meta: seo.meta,
      links: seo.links,
      scripts: [
        jsonLd({
          "@context": "https://schema.org",
          "@type": "Article",
          headline: title,
          description,
          datePublished: date,
          dateModified: date,
          author: { "@type": "Organization", name: SITE_NAME },
          publisher: {
            "@type": "Organization",
            name: SITE_NAME,
            logo: { "@type": "ImageObject", url: SITE_LOGO },
          },
          image: DEFAULT_OG_IMAGE,
          mainEntityOfPage: absUrl(path),
          articleSection: "Daily Devotional",
          keywords: [ref, "Bible devotional", "daily Bible verse"].join(", "),
        }),
        breadcrumb([
          { name: "Home", path: "/" },
          { name: "Archive", path: "/archive" },
          { name: pretty, path },
        ]),
      ],
    };
  },
  component: DailyPage,
  notFoundComponent: () => (
    <div className="mx-auto max-w-3xl px-4 py-14">
      <EmptyState />
    </div>
  ),
});

function DailyPage() {
  const { date } = Route.useParams();
  return (
    <Suspense fallback={<div className="mx-auto max-w-3xl px-4 py-16"><LoadingState /></div>}>
      <DailyContent date={date} />
    </Suspense>
  );
}

function DailyContent({ date }: { date: string }) {
  const { data } = useSuspenseQuery(dailyQuery(date));
  if (!data) {
    return (
      <div className="mx-auto max-w-3xl px-4 py-16 sm:px-6">
        <Link to="/archive" className="text-sm text-muted-foreground hover:text-primary">← Back to archive</Link>
        <EmptyState />
      </div>
    );
  }
  const reference = data.scripture_reference || "Scripture";
  const passage = useQuery({
    queryKey: ["bible-passage", reference, "kjv"],
    queryFn: () => getBiblePassage({ data: { reference, translation: "kjv" } }),
    staleTime: 30 * 24 * 60 * 60 * 1000,
    enabled: Boolean(reference),
  });
  const pretty = formatDate(date);
  const prayer = `Heavenly Father, thank You for Your Word in ${reference}. Help me to hear what You are saying and to walk it out today. In Jesus' name, amen.`;
  const reflection = `What is one way I can respond to ${reference} this week?`;
  return (
    <div className="mx-auto max-w-3xl px-4 py-14 sm:px-6">
      <Link to="/archive" className="text-sm text-muted-foreground hover:text-primary">← Archive</Link>
      <h1 className="mt-3 font-serif text-4xl font-semibold text-primary sm:text-5xl">
        Daily Bible Word for {pretty}
      </h1>
      <p className="mt-2 text-sm text-muted-foreground">{reference}</p>
      <div className="mt-8 space-y-5">
        <BiblePassageCard
          reference={reference}
          translation={passage.data?.translation ?? "KJV"}
          verses={passage.data?.verses ?? []}
          fullText={passage.data?.fullText ?? ""}
          isLoading={passage.isLoading}
          error={passage.data?.error ?? (passage.isError ? "Error" : null)}
        />
        <DevotionalMessageCard text={data.text || ""} topics={Array.isArray(data.topics) ? data.topics : []} date={data.date} />
        <div className="grid gap-5 md:grid-cols-2">
          <PrayerBox text={prayer} />
          <ReflectionBox text={reflection} />
        </div>
        <ShareButton reference={reference} text={(data.text || "").slice(0, 160)} />
      </div>
    </div>
  );
}
