"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  ArrowRight,
  ArrowUpRight,
  Flame,
  Loader2,
  PawPrint,
  Search,
  TrendingUp,
  X,
} from "lucide-react";
import { formatPrice } from "@/lib/format";
import type { ProductCard, SearchSuggestion } from "@/lib/queries";
import { RatingStars } from "./rating-stars";

const POPULAR_TERMS = [
  "kedi maması",
  "köpek maması",
  "ödül maması",
  "kedi yatağı",
  "akvaryum",
  "somonlu",
  "tahılsız",
  "yavru",
];

function Highlight({ text, query }: { text: string; query: string }) {
  const q = query.trim();
  if (!q) return <>{text}</>;
  const idx = text.toLocaleLowerCase("tr").indexOf(q.toLocaleLowerCase("tr"));
  if (idx === -1) return <>{text}</>;
  return (
    <>
      {text.slice(0, idx)}
      <mark className="rounded bg-brand-200/80 px-0.5 text-brand-900">
        {text.slice(idx, idx + q.length)}
      </mark>
      {text.slice(idx + q.length)}
    </>
  );
}

type FlatItem =
  | { kind: "brand"; href: string; key: string }
  | { kind: "product"; href: string; key: string };

export function LiveSearch({ autoFocus = false }: { autoFocus?: boolean }) {
  const router = useRouter();
  const containerRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const abortRef = useRef<AbortController | null>(null);

  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<SearchSuggestion | null>(null);
  const [activeIdx, setActiveIdx] = useState(-1);

  const fetchSuggestions = useCallback(async (q: string) => {
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;
    setLoading(true);
    try {
      const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`, {
        signal: controller.signal,
      });
      const json = (await res.json()) as SearchSuggestion;
      setData(json);
      setActiveIdx(-1);
    } catch {
      /* iptal edildi */
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (!open) return;
    const t = setTimeout(() => fetchSuggestions(query), 200);
    return () => clearTimeout(t);
  }, [query, open, fetchSuggestions]);

  useEffect(() => {
    const onDown = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", onDown);
    return () => document.removeEventListener("mousedown", onDown);
  }, []);

  const flatItems = useMemo<FlatItem[]>(() => {
    if (!data) return [];
    return [
      ...data.brands.map((b) => ({
        kind: "brand" as const,
        href: `/urunler?marka=${b.slug}`,
        key: `b-${b.id}`,
      })),
      ...data.products.map((p) => ({
        kind: "product" as const,
        href: `/urun/${p.slug}`,
        key: `p-${p.id}`,
      })),
    ];
  }, [data]);

  const goToAll = useCallback(() => {
    const q = query.trim();
    setOpen(false);
    router.push(q ? `/urunler?q=${encodeURIComponent(q)}` : "/urunler");
  }, [query, router]);

  const onKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setActiveIdx((i) => Math.min(i + 1, flatItems.length - 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActiveIdx((i) => Math.max(i - 1, -1));
    } else if (e.key === "Enter") {
      e.preventDefault();
      if (activeIdx >= 0 && flatItems[activeIdx]) {
        setOpen(false);
        router.push(flatItems[activeIdx].href);
      } else {
        goToAll();
      }
    } else if (e.key === "Escape") {
      setOpen(false);
      inputRef.current?.blur();
    }
  };

  const showEmptyHint = query.trim() === "";

  return (
    <div ref={containerRef} className="relative w-full">
      <div className="group flex items-center gap-2 rounded-full border-2 border-sand-dark bg-white py-1.5 pl-4 pr-1.5 transition-colors focus-within:border-brand-400 focus-within:shadow-[0_8px_30px_-10px_rgba(249,115,22,0.35)]">
        <Search className="size-5 shrink-0 text-brand-500" aria-hidden />
        <input
          ref={inputRef}
          type="text"
          value={query}
          autoFocus={autoFocus}
          onChange={(e) => {
            setQuery(e.target.value);
            setOpen(true);
          }}
          onFocus={() => setOpen(true)}
          onKeyDown={onKeyDown}
          placeholder="Ürün, marka veya kategori ara… (örn. “kedi maması”)"
          className="w-full bg-transparent text-sm font-bold text-ink outline-none placeholder:font-semibold placeholder:text-latte"
          aria-label="Ürün ara"
          role="combobox"
          aria-expanded={open}
        />
        {query && (
          <button
            type="button"
            onClick={() => {
              setQuery("");
              inputRef.current?.focus();
            }}
            className="grid size-7 shrink-0 place-items-center rounded-full text-mocha transition-colors hover:bg-sand hover:text-ink"
            aria-label="Aramayı temizle"
          >
            <X className="size-4" />
          </button>
        )}
        <button
          type="button"
          onClick={goToAll}
          className="flex shrink-0 items-center gap-1.5 rounded-full bg-brand-500 px-4 py-2 text-sm font-extrabold text-white shadow-lg shadow-brand-500/30 transition-all hover:bg-brand-600 active:scale-95"
        >
          {loading ? (
            <Loader2 className="size-4 animate-spin" aria-hidden />
          ) : (
            <Search className="size-4" aria-hidden />
          )}
          <span className="hidden sm:inline">Ara</span>
        </button>
      </div>

      {open && (
        <div className="absolute left-0 right-0 top-full z-50 mt-2 animate-pop-in overflow-hidden rounded-3xl border border-sand-dark bg-white shadow-2xl shadow-brand-900/15">
          {showEmptyHint ? (
            <div className="p-4">
              <p className="mb-2 flex items-center gap-1.5 text-xs font-extrabold uppercase tracking-wider text-mocha">
                <TrendingUp className="size-3.5 text-brand-500" aria-hidden /> Popüler Aramalar
              </p>
              <div className="mb-4 flex flex-wrap gap-1.5">
                {POPULAR_TERMS.map((term) => (
                  <button
                    key={term}
                    type="button"
                    onClick={() => setQuery(term)}
                    className="rounded-full bg-sand px-3 py-1.5 text-xs font-extrabold text-cocoa transition-colors hover:bg-brand-100 hover:text-brand-800"
                  >
                    {term}
                  </button>
                ))}
              </div>
              {data && data.products.length > 0 && (
                <>
                  <p className="mb-2 flex items-center gap-1.5 text-xs font-extrabold uppercase tracking-wider text-mocha">
                    <Flame className="size-3.5 text-brand-500" aria-hidden /> Patilerin Favorileri
                  </p>
                  <ul className="space-y-1">
                    {data.products.slice(0, 4).map((p) => (
                      <ProductRow key={p.id} product={p} query="" onNavigate={() => setOpen(false)} />
                    ))}
                  </ul>
                </>
              )}
            </div>
          ) : (
            <div className="max-h-[26rem] overflow-y-auto p-2">
              {!data || (data.products.length === 0 && data.brands.length === 0) ? (
                loading ? (
                  <div className="flex items-center justify-center gap-2 py-8 text-sm font-bold text-mocha">
                    <Loader2 className="size-4 animate-spin text-brand-500" aria-hidden />
                    Patiler aranıyor…
                  </div>
                ) : (
                  <div className="flex flex-col items-center gap-2 py-8 text-center">
                    <PawPrint className="size-8 text-brand-300" aria-hidden />
                    <p className="text-sm font-extrabold text-ink">
                      “{query}” için sonuç bulunamadı
                    </p>
                    <p className="text-xs font-semibold text-mocha">
                      Farklı bir kelime deneyin: “mama”, “ödül”, “oyuncak”…
                    </p>
                  </div>
                )
              ) : (
                <>
                  {data.brands.length > 0 && (
                    <div className="px-2 pb-1 pt-2">
                      <p className="mb-1 text-[11px] font-extrabold uppercase tracking-wider text-mocha">
                        Markalar
                      </p>
                      <div className="flex flex-wrap gap-1.5">
                        {data.brands.map((b) => {
                          const itemIndex = flatItems.findIndex((i) => i.key === `b-${b.id}`);
                          return (
                            <Link
                              key={b.id}
                              href={`/urunler?marka=${b.slug}`}
                              onClick={() => setOpen(false)}
                              className={`flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-extrabold transition-colors ${
                                itemIndex === activeIdx
                                  ? "border-brand-400 bg-brand-100 text-brand-800"
                                  : "border-sand-dark bg-cream text-cocoa hover:border-brand-300 hover:text-brand-700"
                              }`}
                            >
                              <Highlight text={b.name} query={query} />
                              <span className="rounded-full bg-brand-500/10 px-1.5 py-0.5 text-[10px] text-brand-600">
                                {b.count} ürün
                              </span>
                            </Link>
                          );
                        })}
                      </div>
                    </div>
                  )}
                  {data.products.length > 0 && (
                    <div className="px-2 pb-1 pt-2">
                      <p className="mb-1 text-[11px] font-extrabold uppercase tracking-wider text-mocha">
                        Ürünler
                      </p>
                      <ul className="space-y-1">
                        {data.products.map((p) => {
                          const itemIndex = flatItems.findIndex((i) => i.key === `p-${p.id}`);
                          return (
                            <ProductRow
                              key={p.id}
                              product={p}
                              query={query}
                              active={itemIndex === activeIdx}
                              onNavigate={() => setOpen(false)}
                            />
                          );
                        })}
                      </ul>
                    </div>
                  )}
                </>
              )}
            </div>
          )}

          {!showEmptyHint && data && data.total > 0 && (
            <button
              type="button"
              onClick={goToAll}
              className="flex w-full items-center justify-center gap-1.5 border-t border-sand bg-brand-50 px-4 py-2.5 text-sm font-extrabold text-brand-700 transition-colors hover:bg-brand-100"
            >
              “{query.trim()}” için tüm {data.total} sonucu gör
              <ArrowRight className="size-4" aria-hidden />
            </button>
          )}
        </div>
      )}
    </div>
  );
}

function ProductRow({
  product,
  query,
  active = false,
  onNavigate,
}: {
  product: ProductCard;
  query: string;
  active?: boolean;
  onNavigate: () => void;
}) {
  return (
    <li>
      <Link
        href={`/urun/${product.slug}`}
        onClick={onNavigate}
        className={`group flex items-center gap-3 rounded-2xl p-1.5 transition-colors ${
          active ? "bg-brand-100" : "hover:bg-sand/70"
        }`}
      >
        <span className="relative block size-12 shrink-0 overflow-hidden rounded-xl bg-sand">
          <Image
            src={product.image}
            alt={product.name}
            fill
            sizes="48px"
            className="object-cover"
          />
        </span>
        <span className="min-w-0 flex-1">
          <span className="block text-[11px] font-extrabold uppercase tracking-wide text-brand-600">
            {product.brand}
          </span>
          <span className="block truncate text-sm font-extrabold text-ink">
            <Highlight text={product.name} query={query} />
          </span>
          <RatingStars rating={product.rating} size="size-3" />
        </span>
        <span className="shrink-0 text-right">
          <span className="block font-display text-sm font-bold text-brand-600">
            {formatPrice(product.price)}
          </span>
        </span>
        <ArrowUpRight className="size-4 shrink-0 text-latte transition-transform group-hover:translate-x-0.5 group-hover:text-brand-500" aria-hidden />
      </Link>
    </li>
  );
}
