import { useMemo, useState, type ReactNode } from "react";
import { businesses, categories } from "@/mocks/dshn";
import { products } from "@/mocks/dshnCommerce";
import { useWeb } from "../WebContext";
import { Container, WCard, PriceWeb, cn } from "../WebUI";
import WebPageHeader from "../components/WebPageHeader";
import {
  DEFAULT_FILTERS,
  PRICE_MAX,
  PRICE_MIN,
  ProductFilterPanel,
  applyDrawerFilters,
  countActiveFilters,
  type ProductFilterState,
} from "../components/ProductFilterDrawer";

export default function Products() {
  const { params, navigate } = useWeb();
  const [cat, setCat] = useState(params.categoryId ?? "");
  const [search, setSearch] = useState("");
  const [filters, setFilters] = useState<ProductFilterState>(DEFAULT_FILTERS);

  const activeCat = categories.find((c) => c.id === cat);
  const title = activeCat ? activeCat.name : "المنتجات";

  // Products after the category + search only, then the sidebar filters on top.
  const baseList = useMemo(
    () =>
      products.filter((p) => {
        if (cat && p.categoryId !== cat) return false;
        if (search && !p.name.includes(search)) return false;
        return true;
      }),
    [cat, search],
  );

  const list = useMemo(() => applyDrawerFilters(baseList, filters), [baseList, filters]);

  const filterCount = countActiveFilters(filters);

  const bizName = (id: string) => businesses.find((b) => b.id === id)?.name ?? "";

  const clearAll = () => setFilters(DEFAULT_FILTERS);
  const removeBiz = (id: string) =>
    setFilters((f) => ({ ...f, bizIds: f.bizIds.filter((x) => x !== id) }));
  const removeCity = (city: string) =>
    setFilters((f) => ({ ...f, cities: f.cities.filter((x) => x !== city) }));
  const clearPrice = () => setFilters((f) => ({ ...f, lo: PRICE_MIN, hi: PRICE_MAX }));

  const priceOn = filters.lo > PRICE_MIN || filters.hi < PRICE_MAX;

  return (
    <div className="animate-fade-in">
      <WebPageHeader title={title} desc={`${list.length} منتج`} crumb="المنتجات" />

      <Container className="py-8">
        <div className="flex items-start gap-8">
          {/* sidebar filters (right in RTL) */}
          <aside className="w-[300px] shrink-0">
            <div className="flex items-center justify-between gap-3 mb-3.5">
              <h2 className="text-[17px] font-bold text-foreground-950 font-heading">الفلاتر</h2>
              {filterCount > 0 && (
                <button
                  type="button"
                  onClick={clearAll}
                  className="text-[13px] font-semibold text-foreground-600 hover:text-foreground-950 cursor-pointer whitespace-nowrap"
                >
                  مسح الكل
                </button>
              )}
            </div>
            <ProductFilterPanel value={filters} onChange={setFilters} />
          </aside>

          {/* content */}
          <div className="flex-1 min-w-0">
            {/* search */}
            <div className="flex items-center gap-2 h-12 px-4 rounded-[16px] bg-background-100 border border-background-200 focus-within:border-foreground-400 transition-colors">
              <i className="ri-search-line text-[19px] text-foreground-500 leading-none" />
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="ابحث عن منتج"
                className="flex-1 bg-transparent text-[14px] text-foreground-950 placeholder:text-foreground-500 outline-none font-body"
              />
              {search && (
                <button type="button" onClick={() => setSearch("")} className="cursor-pointer shrink-0">
                  <i className="ri-close-circle-fill text-[18px] text-foreground-400 leading-none" />
                </button>
              )}
            </div>

            {/* active filter chips */}
            {filterCount > 0 && (
              <div className="flex flex-wrap items-center gap-2 mt-4">
                {priceOn && (
                  <FilterChip onRemove={clearPrice}>
                    {filters.lo.toLocaleString("en-US")} – {filters.hi.toLocaleString("en-US")} ر.س
                  </FilterChip>
                )}
                {filters.bizIds.map((id) => (
                  <FilterChip key={id} onRemove={() => removeBiz(id)}>
                    {bizName(id)}
                  </FilterChip>
                ))}
                {filters.cities.map((city) => (
                  <FilterChip key={city} onRemove={() => removeCity(city)}>
                    {city}
                  </FilterChip>
                ))}
                <button
                  type="button"
                  onClick={clearAll}
                  className="text-[13px] font-semibold text-foreground-600 hover:text-foreground-950 cursor-pointer px-1 whitespace-nowrap"
                >
                  مسح الكل
                </button>
              </div>
            )}

            {/* category chips */}
            <div className="flex items-center gap-3 flex-wrap mt-6">
              <button
                type="button"
                onClick={() => setCat("")}
                className={cn(
                  "rounded-full h-10 px-4 text-[13px] font-medium whitespace-nowrap cursor-pointer transition-colors flex items-center gap-1.5",
                  !cat
                    ? "bg-primary-500 text-background-50"
                    : "bg-background-100 border border-background-200 text-foreground-700 hover:border-background-300",
                )}
              >
                <i className="ri-apps-2-line text-[16px] leading-none" />
                الكل
              </button>
              {categories.map((c) => (
                <button
                  key={c.id}
                  type="button"
                  onClick={() => setCat(c.id)}
                  className={cn(
                    "rounded-full h-10 px-4 text-[13px] font-medium whitespace-nowrap cursor-pointer transition-colors",
                    cat === c.id
                      ? "bg-primary-500 text-background-50"
                      : "bg-background-100 border border-background-200 text-foreground-700 hover:border-background-300",
                  )}
                >
                  {c.name}
                </button>
              ))}
            </div>

            {/* grid */}
            <div className="mt-7">
              {list.length === 0 ? (
                <WCard className="py-20 text-center">
                  <div className="w-16 h-16 rounded-full bg-background-200 flex items-center justify-center mx-auto mb-5">
                    <i className="ri-shopping-bag-3-line text-[30px] text-foreground-500 leading-none" />
                  </div>
                  <p className="text-[15px] font-semibold text-foreground-950">لا توجد منتجات مطابقة</p>
                  <p className="text-[13px] text-foreground-600 mt-1.5">جرّب تعديل البحث أو الفلاتر.</p>
                </WCard>
              ) : (
                <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-5">
                  {list.map((p) => {
                    const biz = businesses.find((b) => b.id === p.businessId);
                    const out = p.stock === 0;
                    return (
                      <WCard key={p.id} className={cn("overflow-hidden", out && "opacity-60")} onClick={() => navigate("product", { productId: p.id })}>
                        <div className="relative w-full aspect-square bg-background-200">
                          <img src={p.image} alt={p.name} className="w-full h-full object-cover object-top" />
                          {out && (
                            <span className="absolute top-2.5 end-2.5 rounded-full bg-foreground-950/85 text-background-50 text-[10.5px] font-semibold px-2.5 py-1">
                              نفد المخزون
                            </span>
                          )}
                        </div>
                        <div className="p-4">
                          <h3 className="text-[13.5px] font-semibold text-foreground-950 leading-snug line-clamp-2 h-10">{p.name}</h3>
                          <div className="mt-2.5">
                            <PriceWeb price={p.price} negotiable={p.negotiable} size="text-[16px]" />
                          </div>
                          {biz && (
                            <button
                              type="button"
                              onClick={(e) => { e.stopPropagation(); navigate("business", { businessId: biz.id }); }}
                              className="mt-2.5 flex items-center gap-1 text-[11.5px] text-foreground-600 hover:text-foreground-950 cursor-pointer max-w-full"
                            >
                              <i className="ri-store-2-line text-[13px] leading-none shrink-0" />
                              <span className="underline underline-offset-2 break-words text-start">{biz.name}</span>
                            </button>
                          )}
                        </div>
                      </WCard>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </div>
      </Container>
    </div>
  );
}

function FilterChip({
  children,
  onRemove,
}: {
  children: ReactNode;
  onRemove: () => void;
}) {
  return (
    <span className="inline-flex items-center gap-1.5 rounded-full bg-background-100 border border-background-200 ps-3 pe-2 py-1.5 text-[12.5px] font-medium text-foreground-800">
      {children}
      <button
        type="button"
        onClick={onRemove}
        aria-label="إزالة الفلتر"
        className="w-5 h-5 rounded-full flex items-center justify-center text-foreground-500 hover:bg-background-200 hover:text-foreground-950 cursor-pointer"
      >
        <i className="ri-close-line text-[15px] leading-none" />
      </button>
    </span>
  );
}