"use client";

import { useEffect, useMemo, useState } from "react";
import { Filter, LoaderCircle, PackageSearch, SlidersHorizontal } from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { Slider } from "@/components/ui/slider";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { ProductCard } from "@/components/product-card";
import { StoreShell } from "@/components/store-shell";
import { formatPrice, getDiscountPercent, type Product } from "@/lib/commerce";

const PAGE_SIZE = 60;

type CatalogResponse = {
  products?: Product[];
  total?: number;
  categories?: Array<{ name: string }>;
};

export function SearchCatalog({ initialProducts, initialQuery, initialCategory }: { initialProducts: Product[]; initialQuery: string; initialCategory: string }) {
  const [products, setProducts] = useState(initialProducts.slice(0, PAGE_SIZE));
  const [categoryNames, setCategoryNames] = useState([...new Set(initialProducts.map((product) => product.category))]);
  const [query] = useState(initialQuery);
  const [category, setCategory] = useState(initialCategory);
  const [sort, setSort] = useState("featured");
  const [inStock, setInStock] = useState(false);
  const [discounted, setDiscounted] = useState(false);
  const initialMaxPrice = Math.max(...initialProducts.map((product) => product.salePrice), 1_000_000);
  const [maxPrice, setMaxPrice] = useState(initialMaxPrice);
  const [priceRange, setPriceRange] = useState([0, initialMaxPrice]);
  const [total, setTotal] = useState(initialProducts.length);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const controller = new AbortController();
    const params = new URLSearchParams({ limit: String(PAGE_SIZE), offset: "0", sort });
    if (query) params.set("q", query);
    if (category) params.set("category", category);
    setLoading(true);
    fetch(`/api/products?${params}`, { signal: controller.signal })
      .then((response) => response.ok ? response.json() as Promise<CatalogResponse> : null)
      .then((payload) => {
        if (!payload) return;
        const nextProducts = payload.products ?? [];
        setProducts(nextProducts);
        setTotal(payload.total ?? nextProducts.length);
        if (payload.categories?.length) setCategoryNames(payload.categories.map((item) => item.name));
        const nextMax = Math.max(...nextProducts.map((product) => product.salePrice), 1_000_000);
        setMaxPrice(nextMax);
        setPriceRange([0, nextMax]);
      })
      .catch(() => undefined)
      .finally(() => setLoading(false));
    return () => controller.abort();
  }, [query, category, sort]);

  async function loadMore() {
    setLoading(true);
    try {
      const params = new URLSearchParams({ limit: String(PAGE_SIZE), offset: String(products.length), sort });
      if (query) params.set("q", query);
      if (category) params.set("category", category);
      const response = await fetch(`/api/products?${params}`);
      const payload = await response.json() as CatalogResponse;
      if (response.ok && payload.products?.length) setProducts((current) => [...current, ...payload.products!]);
    } finally {
      setLoading(false);
    }
  }

  const visible = useMemo(() => products.filter((product) => (!inStock || product.stock > 0) && (!discounted || getDiscountPercent(product) > 0) && product.salePrice >= priceRange[0] && product.salePrice <= priceRange[1]), [products, inStock, discounted, priceRange]);
  const filters = <Filters categories={categoryNames} category={category} setCategory={setCategory} inStock={inStock} setInStock={setInStock} discounted={discounted} setDiscounted={setDiscounted} priceRange={priceRange} setPriceRange={setPriceRange} maxPrice={maxPrice} />;

  return (
    <StoreShell categories={categoryNames}>
      <div className="container-shell py-7">
        <div className="mb-6 flex items-center justify-between gap-3">
          <div><p className="text-sm text-slate-500">barzinmarket / فروشگاه</p><h1 className="mt-2 text-2xl font-black">{query ? `نتایج «${query}»` : category ? category : "همه کالاها"}</h1><p className="mt-1 text-sm text-slate-500">نمایش {new Intl.NumberFormat("fa-IR").format(visible.length)} از {new Intl.NumberFormat("fa-IR").format(total)} کالا</p></div>
          <Sheet><SheetTrigger asChild><Button variant="outline" className="lg:hidden"><Filter className="ml-2 h-4 w-4" />فیلترها</Button></SheetTrigger><SheetContent side="right" dir="rtl"><SheetHeader><SheetTitle className="text-right">فیلتر کالاها</SheetTitle></SheetHeader><div className="mt-6">{filters}</div></SheetContent></Sheet>
        </div>
        <div className="grid gap-5 lg:grid-cols-[280px_minmax(0,1fr)]">
          <aside className="hidden h-fit rounded-[var(--shop-radius)] border bg-white p-5 lg:block dark:bg-slate-900">{filters}</aside>
          <section>
            <div className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-2xl border bg-white px-4 py-3 dark:bg-slate-900">
              <div className="flex items-center gap-2 text-sm font-bold"><SlidersHorizontal className="h-4 w-4 text-[var(--shop-primary)]" />مرتب‌سازی</div>
              <NativeSelect value={sort} onChange={(event) => setSort(event.target.value)} className="w-48"><NativeSelectOption value="featured">پیشنهاد barzinmarket</NativeSelectOption><NativeSelectOption value="popular">محبوب‌ترین</NativeSelectOption><NativeSelectOption value="newest">جدیدترین</NativeSelectOption><NativeSelectOption value="price-asc">ارزان‌ترین</NativeSelectOption><NativeSelectOption value="price-desc">گران‌ترین</NativeSelectOption></NativeSelect>
            </div>
            {visible.length ? <><div className="catalog-grid">{visible.map((product) => <ProductCard key={product.id} product={product} />)}</div>{products.length < total && <div className="mt-7 flex justify-center"><Button variant="outline" disabled={loading} onClick={loadMore} className="min-w-52 border-emerald-200 text-emerald-800 hover:bg-emerald-50">{loading ? <><LoaderCircle className="ml-2 h-4 w-4 animate-spin" />در حال دریافت…</> : "نمایش کالاهای بیشتر"}</Button></div>}</> : <div className="grid min-h-96 place-items-center rounded-[var(--shop-radius)] border border-dashed bg-white p-8 text-center dark:bg-slate-900"><div>{loading ? <LoaderCircle className="mx-auto h-12 w-12 animate-spin text-[var(--shop-primary)]" /> : <PackageSearch className="mx-auto h-16 w-16 text-slate-300" />}<h2 className="mt-5 text-xl font-black">{loading ? "در حال دریافت کالاها" : "کالایی پیدا نشد"}</h2>{!loading && <p className="mt-2 text-sm text-slate-500">فیلترها را کمتر کنید یا عبارت دیگری بنویسید.</p>}</div></div>}
          </section>
        </div>
      </div>
    </StoreShell>
  );
}

function Filters({ categories, category, setCategory, inStock, setInStock, discounted, setDiscounted, priceRange, setPriceRange, maxPrice }: { categories: string[]; category: string; setCategory: (value: string) => void; inStock: boolean; setInStock: (value: boolean) => void; discounted: boolean; setDiscounted: (value: boolean) => void; priceRange: number[]; setPriceRange: (value: number[]) => void; maxPrice: number }) {
  return <div className="space-y-6"><div><h2 className="font-black">دسته‌بندی</h2><div className="mt-3 grid max-h-56 gap-1 overflow-auto">{["", ...categories].map((item) => <button key={item || "all"} onClick={() => setCategory(item)} className={`rounded-xl px-3 py-2 text-right text-sm ${category === item ? "bg-emerald-50 font-black text-[var(--shop-primary)] dark:bg-emerald-950/40" : "hover:bg-slate-100 dark:hover:bg-slate-800"}`}>{item || "همه دسته‌ها"}</button>)}</div></div><div className="border-t pt-5"><div className="mb-4 flex items-center justify-between"><Label htmlFor="stock">فقط کالاهای موجود</Label><Checkbox id="stock" checked={inStock} onCheckedChange={(value) => setInStock(Boolean(value))} /></div><div className="flex items-center justify-between"><Label htmlFor="discount">فقط کالاهای تخفیف‌دار</Label><Checkbox id="discount" checked={discounted} onCheckedChange={(value) => setDiscounted(Boolean(value))} /></div></div><div className="border-t pt-5"><h3 className="mb-5 font-black">محدوده قیمت</h3><Slider min={0} max={maxPrice} step={1000} value={priceRange} onValueChange={setPriceRange} /><div className="mt-4 flex justify-between text-xs font-bold text-slate-500"><span>{formatPrice(priceRange[0])}</span><span>{formatPrice(priceRange[1])} تومان</span></div></div><Button variant="outline" className="w-full" onClick={() => { setCategory(""); setInStock(false); setDiscounted(false); setPriceRange([0, maxPrice]); }}>پاک کردن فیلترها</Button></div>;
}
