import { createFileRoute } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { searchDevotionals } 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 = ["faith", "fear", "forgiveness", "discouragement", "prayer", "marriage", "wisdom"];

export const Route = createFileRoute("/search")({
  head: () => {
    const seo = pageSeo({
      title: "Search Bible Devotionals | Bible Word of the Day",
      description:
        "Search Bible devotionals by topic, keyword, or life situation and find Scripture-based encouragement for what you are facing.",
      path: "/search",
    });
    return { meta: seo.meta, links: seo.links };
  },
  component: SearchPage,
});

function SearchPage() {
  const [q, setQ] = useState("");
  const search = useServerFn(searchDevotionals);
  const log = useServerFn(logSearch);

  const query = useQuery({
    queryKey: ["search", q],
    queryFn: async () => {
      const res = await search({ data: { q } });
      log({ data: { query: q, type: "search" } }).catch(() => {});
      return res;
    },
    enabled: q.length > 0,
    staleTime: 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)]">Search</p>
        <h1 className="mt-2 font-serif text-4xl font-semibold text-primary sm:text-5xl">
          Search Bible Devotionals
        </h1>
        <p className="mx-auto mt-3 max-w-xl text-base text-muted-foreground">
          Type a feeling, struggle, or question. We'll show you Scripture and reflections that meet you there.
        </p>
      </header>

      <div className="mt-8">
        <SearchBar placeholder="Try: faith, fear, forgiveness…" onSearch={setQ} initial={q} />
      </div>

      {!q && (
        <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={() => setQ(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 && q && <LoadingState label={`Searching for "${q}"…`} />}
        {!query.isFetching && q && (() => {
          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>
  );
}
