import { createFileRoute } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { getVerse } from "@/lib/api/treasure.functions";
import { logSearch } from "@/lib/api/subscribe.functions";
import { normalizeList } from "@/lib/devotional";
import { SearchBar } from "@/components/devotional/SearchBar";
import { DevotionalCard } from "@/components/devotional/DevotionalCard";
import { LoadingState, EmptyState } from "@/components/devotional/States";
import { pageSeo } from "@/lib/seo";

const SUGGESTIONS = ["John 3:16", "Psalm 23", "Romans 8:28", "Philippians 4:13", "Isaiah 41:10"];

export const Route = createFileRoute("/verse")({
  head: () => {
    const seo = pageSeo({
      title: "Bible Verse Lookup | Bible Word of the Day",
      description:
        "Look up a Bible verse or passage and find related devotional messages, Scripture reflections, and practical encouragement.",
      path: "/verse",
    });
    return { meta: seo.meta, links: seo.links };
  },
  component: VersePage,
});

function VersePage() {
  const [v, setV] = useState("");
  const lookup = useServerFn(getVerse);
  const log = useServerFn(logSearch);

  const query = useQuery({
    queryKey: ["verse", v],
    queryFn: async () => {
      const res = await lookup({ data: { verse: v } });
      log({ data: { query: v, type: "verse" } }).catch(() => {});
      return res;
    },
    enabled: v.length > 0,
    staleTime: 7 * 24 * 60 * 60 * 1000,
  });

  return (
    <div className="mx-auto max-w-4xl px-4 py-14 sm:px-6">
      <header className="text-center">
        <p className="text-xs font-medium uppercase tracking-[0.2em] text-[var(--gold)]">Verse lookup</p>
        <h1 className="mt-2 font-serif text-4xl font-semibold text-primary sm:text-5xl">
          Look Up a Bible Verse
        </h1>
        <p className="mx-auto mt-3 max-w-xl text-base text-muted-foreground">
          Enter a reference and we'll find related devotional reflections.
        </p>
      </header>

      <div className="mt-8">
        <SearchBar placeholder="John 3:16, Psalm 23, Romans 8:28" onSearch={setV} initial={v} />
      </div>

      {!v && (
        <div className="mt-6 flex flex-wrap items-center justify-center gap-2 text-sm text-muted-foreground">
          <span>Try:</span>
          {SUGGESTIONS.map((s) => (
            <button
              key={s}
              onClick={() => setV(s)}
              className="rounded-full border border-border bg-card px-3 py-1 text-xs text-primary hover:border-[var(--gold)]"
            >
              {s}
            </button>
          ))}
        </div>
      )}

      <div className="mt-10">
        {query.isFetching && v && <LoadingState label={`Looking up ${v}…`} />}
        {!query.isFetching && v && (() => {
          const list = normalizeList(query.data);
          if (list.length === 0) return <EmptyState />;
          return (
            <div className="grid gap-5 md:grid-cols-2">
              {list.map((d, i) => <DevotionalCard key={d.id ?? i} devotional={d} compact />)}
            </div>
          );
        })()}
      </div>
    </div>
  );
}
