"use client";

/**
 * جستجو با پیشنهاد خودکار.
 * با تایپ کاربر (با تأخیر ۲۰۰ میلی‌ثانیه) از /api/search/suggest پیشنهاد می‌گیرد.
 * وقتی فیلد خالی است، جستجوهای اخیر و پرتکرار نمایش داده می‌شوند.
 */
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { popularSearches } from "@/data/content";
import { recentSearches, useRecentSearches } from "@/lib/client/store";
import { Icon } from "@/components/ui/Icon";
import { Price } from "@/components/ui/Price";
import { ProductVisual } from "@/components/product/ProductVisual";
import { productHref } from "@/components/product/ProductCard";
import type { ProductSummary } from "@/types/catalog";

interface Suggestions {
  products: ProductSummary[];
  brands: { name: string; slug: string }[];
  categories: { name: string; href: string }[];
}

const EMPTY: Suggestions = { products: [], brands: [], categories: [] };

export function SearchOverlay() {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState("");
  const [data, setData] = useState<Suggestions>(EMPTY);
  const [loading, setLoading] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const recent = useRecentSearches();

  // دریافت پیشنهادها با تأخیر و لغو درخواست قبلی
  useEffect(() => {
    if (q.trim().length < 2) {
      setData(EMPTY);
      return;
    }
    const ctrl = new AbortController();
    setLoading(true);
    const timer = setTimeout(async () => {
      try {
        const res = await fetch(`/api/search/suggest?q=${encodeURIComponent(q.trim())}`, { signal: ctrl.signal });
        if (res.ok) setData(await res.json());
      } catch {
        /* درخواست لغو شد */
      } finally {
        setLoading(false);
      }
    }, 200);
    return () => {
      clearTimeout(timer);
      ctrl.abort();
    };
  }, [q]);

  useEffect(() => {
    if (!open) return;
    inputRef.current?.focus();
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open]);

  function go(term: string) {
    const t = term.trim();
    if (!t) return;
    recentSearches.push(t);
    setOpen(false);
    router.push(`/search?q=${encodeURIComponent(t)}`);
  }

  const close = () => setOpen(false);
  const hasQuery = q.trim().length >= 2;
  const noResult = hasQuery && !loading && !data.products.length && !data.brands.length && !data.categories.length;

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="flex h-10 w-full items-center gap-2 rounded-full border border-ink/80 px-3.5 text-start text-sm text-subtle md:h-11"
      >
        <Icon name="search" size={19} className="shrink-0 text-ink" />
        <span className="truncate">جستجو در زهورا</span>
      </button>

      {open && (
        <div className="fixed inset-0 z-50 flex animate-fade-in flex-col bg-paper" role="dialog" aria-modal="true" aria-label="جستجو">
          <form
            role="search"
            onSubmit={(e) => {
              e.preventDefault();
              go(q);
            }}
            className="container-z flex h-16 shrink-0 items-center gap-2 border-b border-line md:h-20"
          >
            <Icon name="search" className="shrink-0" />
            <input
              ref={inputRef}
              value={q}
              onChange={(e) => setQ(e.target.value)}
              type="search"
              enterKeyHint="search"
              maxLength={80}
              placeholder="نام محصول، برند یا دسته…"
              className="h-full min-w-0 flex-1 bg-transparent text-base outline-none placeholder:text-subtle"
              aria-label="عبارت جستجو"
            />
            <button type="button" onClick={close} className="shrink-0 px-2 text-sm text-muted">
              انصراف
            </button>
          </form>

          <div className="flex-1 overflow-y-auto">
            <div className="container-z max-w-3xl py-6">
              {!hasQuery && (
                <div className="space-y-8">
                  {recent.length > 0 && (
                    <section>
                      <div className="mb-3 flex items-center justify-between">
                        <h3 className="eyebrow">جستجوهای اخیر</h3>
                        <button onClick={recentSearches.clear} className="text-xs text-muted underline">
                          پاک کردن
                        </button>
                      </div>
                      <div className="flex flex-wrap gap-2">
                        {recent.map((t) => (
                          <button key={t} onClick={() => go(t)} className="chip">
                            <Icon name="clock" size={14} />
                            {t}
                          </button>
                        ))}
                      </div>
                    </section>
                  )}
                  <section>
                    <h3 className="eyebrow mb-3">جستجوهای پرطرفدار</h3>
                    <div className="flex flex-wrap gap-2">
                      {popularSearches.map((t) => (
                        <button key={t} onClick={() => go(t)} className="chip">
                          {t}
                        </button>
                      ))}
                    </div>
                  </section>
                </div>
              )}

              {hasQuery && (
                <div className="space-y-6">
                  {(data.categories.length > 0 || data.brands.length > 0) && (
                    <div className="flex flex-wrap gap-2">
                      {data.categories.map((c) => (
                        <Link key={c.href} href={c.href} onClick={close} className="chip">
                          دسته: {c.name}
                        </Link>
                      ))}
                      {data.brands.map((b) => (
                        <Link key={b.slug} href={`/brand/${b.slug}`} onClick={close} className="chip">
                          برند: {b.name}
                        </Link>
                      ))}
                    </div>
                  )}
                  {data.products.length > 0 && (
                    <ul className="divide-y divide-line">
                      {data.products.map((p) => (
                        <li key={p.id}>
                          <Link href={productHref(p)} onClick={close} className="flex items-center gap-4 py-3">
                            <div className="size-16 shrink-0 overflow-hidden rounded-xl bg-mist">
                              <ProductVisual image={p.image} sizes="64px" shape={p.shape} tone={p.tone} label={p.brand.nameEn} className="size-full" />
                            </div>
                            <div className="min-w-0 flex-1">
                              <p className="text-xs font-bold">{p.brand.name}</p>
                              <p className="truncate text-sm text-ink-soft">{p.name}</p>
                            </div>
                            <Price price={p.price} size="sm" />
                          </Link>
                        </li>
                      ))}
                    </ul>
                  )}
                  {loading && <p className="text-sm text-muted">در حال جستجو…</p>}
                  {noResult && <p className="text-sm text-muted">نتیجه‌ای برای «{q}» پیدا نشد. املای دیگری را امتحان کنید.</p>}
                  {!noResult && (
                    <button onClick={() => go(q)} className="btn-outline w-full">
                      مشاهده همه نتایج «{q.trim()}»
                    </button>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}
