import { createFileRoute, Link } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery, useQuery } from "@tanstack/react-query";
import { Suspense } from "react";
import { pageSeo, jsonLd } from "@/lib/seo";
import { getToday } from "@/lib/api/treasure.functions";
import { getBiblePassage } from "@/lib/api/bible.functions";
import { normalizeToday, FEATURED_TOPICS, FALLBACK_TODAY, type Devotional } from "@/lib/devotional";
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 { TopicTag } from "@/components/devotional/TopicTag";
import { ShareButton } from "@/components/devotional/ShareButton";
import { EmailSignup } from "@/components/devotional/EmailSignup";
import { LoadingState } from "@/components/devotional/States";
import { Sunrise, BookOpen, Heart } from "lucide-react";

const todayQuery = queryOptions({
  queryKey: ["today"],
  queryFn: () => getToday(),
  staleTime: 24 * 60 * 60 * 1000,
});

function passageQuery(reference: string, translation = "kjv") {
  return queryOptions({
    queryKey: ["bible-passage", reference, translation],
    queryFn: () => getBiblePassage({ data: { reference, translation } }),
    staleTime: 30 * 24 * 60 * 60 * 1000,
    enabled: Boolean(reference),
  });
}

export const Route = createFileRoute("/")({
  head: () => {
    const seo = pageSeo({
      title: "Bible Word of the Day | Daily Bible Verse with Explanation",
      description:
        "Read today's Bible verse with a practical devotional message, Scripture passage, prayer, and reflection to help you live God's Word daily.",
      path: "/",
    });
    return {
      meta: seo.meta,
      links: seo.links,
      scripts: [
        jsonLd({
          "@context": "https://schema.org",
          "@type": "WebSite",
          name: "Bible Word of the Day",
          url: "https://biblewordoftheday.com",
          potentialAction: {
            "@type": "SearchAction",
            target: "https://biblewordoftheday.com/search?q={search_term_string}",
            "query-input": "required name=search_term_string",
          },
        }),
      ],
    };
  },
  loader: ({ context }) => context.queryClient.ensureQueryData(todayQuery),
  component: HomePage,
  errorComponent: () => <Hero devotional={FALLBACK_TODAY} />,
  notFoundComponent: () => <Hero devotional={FALLBACK_TODAY} />,
});

function HomePage() {
  return (
    <Suspense
      fallback={
        <div className="mx-auto max-w-3xl px-4 py-16">
          <LoadingState label="Opening today's Word…" />
        </div>
      }
    >
      <HomeContent />
    </Suspense>
  );
}

function HomeContent() {
  const { data } = useSuspenseQuery(todayQuery);
  const normalized = normalizeToday(data);
  const devotional: Devotional = { ...FALLBACK_TODAY, ...normalized };
  return <Hero devotional={devotional} />;
}

function generatePrayer(d: Devotional): string {
  if (d.prayer) return d.prayer;
  return `Heavenly Father, thank You for Your Word in ${d.scripture_reference}. Help me to hear what You are saying through this Scripture and to walk it out in my life today. Give me a soft heart, a steady mind, and the grace to trust You. In Jesus' name, amen.`;
}

function generateReflection(d: Devotional): string {
  if (d.reflection) return d.reflection;
  return `What is one specific way you can respond to ${d.scripture_reference} in your life this week?`;
}

function Hero({ devotional }: { devotional: Devotional }) {
  const today = new Date().toLocaleDateString(undefined, {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
  });
  const reference = devotional.context || devotional.scripture_reference;
  const passage = useQuery(passageQuery(reference, "kjv"));

  const prayer = generatePrayer(devotional);
  const reflection = generateReflection(devotional);

  const shareExcerpt =
    passage.data?.fullText?.slice(0, 160) ||
    devotional.text.slice(0, 160);

  return (
    <>
      <section className="gradient-hero parchment border-b border-border/60">
        <div className="mx-auto max-w-3xl px-4 py-14 sm:px-6 sm:py-20">
          <div className="text-center">
            <p className="inline-flex items-center gap-2 rounded-full border border-[var(--gold)]/30 bg-card/60 px-4 py-1.5 text-xs font-medium uppercase tracking-[0.2em] text-primary">
              <Sunrise className="h-3.5 w-3.5 text-[var(--gold)]" />
              {today}
            </p>
            <h1 className="text-balance mt-6 font-serif text-4xl font-semibold leading-tight text-primary sm:text-6xl">
              Today's Bible Word
            </h1>
            <p className="mx-auto mt-4 max-w-xl text-balance text-base text-muted-foreground sm:text-lg">
              Read the Scripture, reflect on its meaning, and carry God's Word into your day.
            </p>
          </div>

          <div className="mt-10 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={devotional.text}
              topics={devotional.topics}
              date={devotional.date}
            />

            <div className="grid gap-5 md:grid-cols-2">
              <PrayerBox text={prayer} />
              <ReflectionBox text={reflection} />
            </div>

            <div className="flex flex-wrap items-center justify-center gap-3 pt-2">
              <ShareButton reference={reference} text={shareExcerpt} />
              <a
                href="#email"
                className="gradient-gold rounded-full px-6 py-3 text-sm font-semibold text-[var(--gold-foreground)] shadow-soft hover:opacity-95"
              >
                Get the Daily Word by Email
              </a>
              <Link
                to="/topics"
                className="rounded-full border border-primary/15 bg-card px-6 py-3 text-sm font-semibold text-primary shadow-soft hover:border-[var(--gold)]"
              >
                Browse Topics
              </Link>
            </div>
          </div>
        </div>
      </section>

      <section className="mx-auto max-w-6xl px-4 py-16 sm:px-6">
        <div className="flex items-end justify-between gap-4">
          <div>
            <h2 className="font-serif text-3xl font-semibold text-primary sm:text-4xl">
              Featured Topics
            </h2>
            <p className="mt-2 text-sm text-muted-foreground">
              Find a Bible Word for what you're facing.
            </p>
          </div>
          <Link to="/topics" className="text-sm font-medium text-primary hover:text-[var(--gold)]">
            View all →
          </Link>
        </div>
        <div className="mt-6 flex flex-wrap gap-2.5">
          {FEATURED_TOPICS.map((t) => (
            <TopicTag key={t} topic={t} />
          ))}
        </div>
      </section>

      <section className="mx-auto max-w-6xl px-4 pb-20 sm:px-6">
        <h2 className="font-serif text-3xl font-semibold text-primary sm:text-4xl">
          Why Bible Word of the Day?
        </h2>
        <div className="mt-8 grid gap-6 md:grid-cols-3">
          <FeatureCard
            icon={<BookOpen className="h-5 w-5" />}
            title="Scripture-centered"
            body="Each day begins with a verse — not opinion. The Bible leads, we follow."
          />
          <FeatureCard
            icon={<Sunrise className="h-5 w-5" />}
            title="Practical reflection"
            body="A short, clear explanation that fits in the margins of a busy day."
          />
          <FeatureCard
            icon={<Heart className="h-5 w-5" />}
            title="Prayer & response"
            body="A simple prayer and reflection question to take Scripture into your day."
          />
        </div>
      </section>

      <section id="email" className="border-t border-border bg-card/60">
        <div className="mx-auto max-w-2xl px-4 py-20 sm:px-6">
          <EmailSignup />
        </div>
      </section>
    </>
  );
}

function FeatureCard({ icon, title, body }: { icon: React.ReactNode; title: string; body: string }) {
  return (
    <div className="rounded-2xl border border-border bg-card p-6 shadow-soft">
      <div className="inline-flex h-10 w-10 items-center justify-center rounded-lg bg-[var(--gold)]/15 text-[var(--gold)]">
        {icon}
      </div>
      <h3 className="mt-4 font-serif text-xl font-semibold text-primary">{title}</h3>
      <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{body}</p>
    </div>
  );
}
