import { useState } from "react";
import { useApp } from "../AppContext";
import { businesses, categories } from "@/mocks/dshn";
import ProductCard from "../components/ProductCard";
import { EmptyState, SearchInput, cn } from "../components/ui";
import { PRICE_MAX, PRICE_MIN, filterProducts, parseIdList } from "../lib/productFilters";
import type { NavParams } from "../types";

interface ActiveChip {
  id: string;
  label: string;
  onRemove: () => void;
}

export default function Products() {
  const { params, navigate } = useApp();
  const businessId = params.businessId;

  const [categoryId, setCategoryId] = useState<string | null>(params.categoryId ?? null);
  const [query, setQuery] = useState("");
  const [minPrice, setMinPrice] = useState<number | null>(params.minPrice ? Number(params.minPrice) : null);
  const [maxPrice, setMaxPrice] = useState<number | null>(params.maxPrice ? Number(params.maxPrice) : null);
  const [bizIds, setBizIds] = useState<string[]>(parseIdList(params.bizIds));
  const [cities, setCities] = useState<string[]>(parseIdList(params.cities));

  const biz = businesses.find((b) => b.id === businessId);
  const activeCat = categories.find((c) => c.id === categoryId);

  let list = filterProducts({ categoryId, query, minPrice, maxPrice, businessIds: bizIds, cities });
  if (businessId) list = list.filter((p) => p.businessId === businessId);

  const title = biz ? `منتجات ${biz.name}` : activeCat ? activeCat.name : "المنتجات";
  const activeFilterCount = (minPrice != null || maxPrice != null ? 1 : 0) + bizIds.length + cities.length;

  const chips: ActiveChip[] = [];
  if (minPrice != null || maxPrice != null) {
    const lo = minPrice ?? PRICE_MIN;
    const hi = maxPrice ?? PRICE_MAX;
    chips.push({
      id: "price",
      label: `${lo.toLocaleString("en-US")}–${hi.toLocaleString("en-US")} ر.س`,
      onRemove: () => {
        setMinPrice(null);
        setMaxPrice(null);
      },
    });
  }
  cities.forEach((city) =>
    chips.push({
      id: `city-${city}`,
      label: city,
      onRemove: () => setCities((l) => l.filter((x) => x !== city)),
    }),
  );
  bizIds.forEach((id) => {
    const b = businesses.find((x) => x.id === id);
    chips.push({
      id: `biz-${id}`,
      label: b?.name ?? id,
      onRemove: () => setBizIds((l) => l.filter((x) => x !== id)),
    });
  });

  const openFilter = () => {
    const p: NavParams = {};
    if (categoryId) p.categoryId = categoryId;
    if (minPrice != null) p.minPrice = String(minPrice);
    if (maxPrice != null) p.maxPrice = String(maxPrice);
    if (bizIds.length) p.bizIds = bizIds.join(",");
    if (cities.length) p.cities = cities.join(",");
    navigate("productsFilter", p);
  };

  const resetAll = () => {
    setQuery("");
    setMinPrice(null);
    setMaxPrice(null);
    setBizIds([]);
    setCities([]);
  };

  return (
    <div className="w-full max-w-full min-w-0 pb-6">
      <div className="px-4">
        <h1 className="text-[24px] font-bold text-foreground-950 leading-tight break-words">{title}</h1>
      </div>

      {/* Search + filter row */}
      <div className="w-full max-w-full px-4 mt-4">
        <SearchInput
          value={query}
          onChange={setQuery}
          placeholder="ابحث عن منتج"
          onFilter={openFilter}
          filterCount={activeFilterCount}
        />
      </div>

      {/* Active filter chips */}
      {chips.length > 0 && (
        <div className="flex gap-2 overflow-x-auto no-scrollbar px-4 mt-3">
          {chips.map((chip) => (
            <button
              key={chip.id}
              type="button"
              onClick={chip.onRemove}
              className="flex items-center gap-1.5 rounded-full h-9 pl-1.5 pr-3 bg-background-100 border border-foreground-300 text-[12.5px] font-medium text-foreground-900 whitespace-nowrap cursor-pointer shrink-0 hover:border-foreground-400 transition-colors"
            >
              {chip.label}
              <i className="ri-close-line text-[15px] leading-none text-foreground-500" />
            </button>
          ))}
        </div>
      )}

      {/* Category circles */}
      <div className="flex gap-4 overflow-x-auto no-scrollbar px-4 mt-4 pb-1">
        <button
          type="button"
          onClick={() => setCategoryId(null)}
          className="shrink-0 flex flex-col items-center gap-2 w-[70px] cursor-pointer"
        >
          <div
            className={cn(
              "w-[60px] h-[60px] rounded-full flex items-center justify-center border-2 transition-colors",
              !categoryId ? "bg-foreground-950 border-foreground-950" : "bg-background-100 border-background-200",
            )}
          >
            <i className={cn("ri-apps-2-line text-[23px] leading-none", !categoryId ? "text-background-50" : "text-foreground-600")} />
          </div>
          <span className={cn("text-[10.5px] text-center leading-tight", !categoryId ? "text-foreground-950 font-semibold" : "text-foreground-600")}>
            الكل
          </span>
        </button>
        {categories.map((c) => {
          const active = categoryId === c.id;
          return (
            <button
              key={c.id}
              type="button"
              onClick={() => setCategoryId(c.id)}
              className="shrink-0 flex flex-col items-center gap-2 w-[70px] cursor-pointer"
            >
              <div
                className={cn(
                  "w-[60px] h-[60px] rounded-full overflow-hidden border-2 transition-colors",
                  active ? "border-foreground-950" : "border-background-200",
                )}
              >
                <img src={c.image} alt={c.name} className="w-full h-full object-cover object-top" />
              </div>
              <span className={cn("text-[10.5px] text-center leading-tight", active ? "text-foreground-950 font-semibold" : "text-foreground-600")}>
                {c.name}
              </span>
            </button>
          );
        })}
      </div>

      {/* Results */}
      <div className="px-4 mt-4">
        <div className="flex items-center justify-between mb-3">
          <span className="text-[12.5px] text-foreground-600">{list.length} منتج متاح</span>
        </div>
        {list.length === 0 ? (
          <EmptyState
            icon="ri-search-eye-line"
            title="لا توجد منتجات مطابقة"
            desc="جرّب تعديل الفلاتر أو البحث باسم مختلف."
            actionLabel="إعادة تعيين الفلاتر"
            onAction={() => {
              setCategoryId(null);
              resetAll();
            }}
          />
        ) : (
          <div className="grid grid-cols-2 gap-3">
            {list.map((p) => (
              <ProductCard
                key={p.id}
                product={p}
                onClick={() => navigate("product", { productId: p.id })}
                onClickBusiness={() => navigate("business", { businessId: p.businessId })}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}