import { useState } from "react";
import { createFileRoute, Link } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { Loader2, Search, Sparkle } from "lucide-react";
import { toast } from "sonner";
import { ContentPageView } from "@/components/content-page";
import { getContentPage } from "@/lib/site-content";
import { keywordMeta } from "@/lib/seo-keywords";
import { searchSite, type SearchHit } from "@/lib/search.functions";

export const Route = createFileRoute("/gatavase-search")({
  head: () => {
    const page = getContentPage("/gatavase-search");
    return {
      meta: [
        { title: page.metaTitle },
        { name: "description", content: page.description },
        keywordMeta(page.clusters),
        { property: "og:title", content: page.metaTitle },
        { property: "og:description", content: page.description },
        { property: "og:url", content: page.slug },
        { property: "og:type", content: "website" },
        { name: "twitter:card", content: "summary" },
      ],
      links: [{ rel: "canonical", href: page.slug }],
    };
  },
  component: PageRoute,
});

const SUGGESTIONS = ["AI automation", "mobile app development", "cyber security", "training"];

function PageRoute() {
  const run = useServerFn(searchSite);
  const [query, setQuery] = useState("");
  const [answer, setAnswer] = useState("");
  const [results, setResults] = useState<SearchHit[]>([]);
  const [searched, setSearched] = useState(false);
  const [loading, setLoading] = useState(false);

  const submit = async (value: string) => {
    const q = value.trim();
    if (q.length < 2) return;
    setLoading(true);
    setSearched(true);
    try {
      const res = await run({ data: { query: q } });
      setAnswer(res.answer);
      setResults(res.results);
    } catch {
      toast.error("Search is unavailable right now.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <section className="border-b border-border hero-surface">
        <div className="mx-auto max-w-4xl px-5 py-20">
          <p className="font-mono text-xs uppercase tracking-[0.2em] text-primary">Products</p>
          <h1 className="mt-3 text-4xl font-bold md:text-5xl">
            Gatavase <span className="text-gradient">Search</span>
          </h1>
          <p className="mt-4 text-muted-foreground">
            Search every Gatavase service, product, division and article — with an AI summary of
            what we found.
          </p>

          <form
            onSubmit={(e) => {
              e.preventDefault();
              void submit(query);
            }}
            className="mt-8 flex items-center gap-2 rounded-full border border-primary/30 bg-card/70 p-2 backdrop-blur"
          >
            <Search className="ml-3 size-4 text-primary" />
            <input
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Search Gatavase — e.g. blockchain, robotics, e-learning"
              aria-label="Search Gatavase"
              className="flex-1 bg-transparent px-1 py-2 text-sm outline-none"
            />
            <button
              type="submit"
              disabled={loading}
              className="rounded-full bg-primary px-5 py-2 text-sm font-semibold text-primary-foreground disabled:opacity-60"
            >
              {loading ? <Loader2 className="size-4 animate-spin" /> : "Search"}
            </button>
          </form>

          <div className="mt-4 flex flex-wrap gap-2">
            {SUGGESTIONS.map((s) => (
              <button
                key={s}
                onClick={() => {
                  setQuery(s);
                  void submit(s);
                }}
                className="rounded-full border border-input px-3.5 py-1.5 text-xs text-muted-foreground hover:border-primary/50 hover:text-primary"
              >
                {s}
              </button>
            ))}
          </div>

          {searched && (
            <div className="mt-10 space-y-6">
              {answer && (
                <div className="rounded-2xl border border-primary/30 bg-primary/5 p-5">
                  <p className="flex items-center gap-2 font-mono text-[11px] uppercase tracking-widest text-primary">
                    <Sparkle className="size-3.5" /> AI overview
                  </p>
                  <p className="mt-3 whitespace-pre-wrap text-sm leading-relaxed">{answer}</p>
                </div>
              )}
              {!loading && results.length === 0 && (
                <p className="text-sm text-muted-foreground">
                  No matches yet. Try a broader term, or{" "}
                  <Link to="/contact" className="text-primary">
                    ask our team
                  </Link>
                  .
                </p>
              )}
              <ul className="space-y-3">
                {results.map((r) => (
                  <li
                    key={`${r.path}-${r.title}`}
                    className="rounded-2xl border border-border bg-card/60 p-4 backdrop-blur transition-colors hover:border-primary/40"
                  >
                    <p className="font-mono text-[11px] uppercase tracking-widest text-primary">
                      {r.group}
                    </p>
                    <a href={r.path} className="mt-1 block text-base font-semibold">
                      {r.title}
                    </a>
                    <p className="mt-1 text-sm text-muted-foreground">{r.snippet}</p>
                    <p className="mt-2 font-mono text-[11px] text-muted-foreground">{r.path}</p>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      </section>

      <ContentPageView page={getContentPage("/gatavase-search")} />
    </>
  );
}
