"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import type { Product } from "@/lib/api";
import ProductCard from "./ProductCard";

const PER = 24;

type SubFacet = { name: string; slug: string };
type SubNav = {
  catName: string;
  allHref: string;
  activeSlug: string;
  items: { name: string; slug: string; href: string }[];
};

type Props = {
  products: Product[];
  /** Category page: subcategories become multi-select filters (matched on product.category). */
  subFacets?: SubFacet[];
  /** Subcategory page: sibling subcategories shown as navigation links. */
  subNav?: SubNav;
};

function csv(v: string[]): string {
  return v.filter(Boolean).join(",");
}
function fromCsv(v: string | null): string[] {
  return v ? v.split(",").filter(Boolean) : [];
}

export default function ProductCatalog({ products, subFacets, subNav }: Props) {
  // ---- price bounds from the data ----
  const [boundMin, boundMax] = useMemo(() => {
    if (!products.length) return [0, 0];
    let lo = Infinity;
    let hi = -Infinity;
    for (const p of products) {
      if (p.price < lo) lo = p.price;
      if (p.price > hi) hi = p.price;
    }
    return [Math.floor(lo), Math.ceil(hi)];
  }, [products]);

  const [selSubs, setSelSubs] = useState<string[]>([]);
  const [selBrands, setSelBrands] = useState<string[]>([]);
  const [priceLo, setPriceLo] = useState(boundMin);
  const [priceHi, setPriceHi] = useState(boundMax);
  const [sort, setSort] = useState("featured");
  const [page, setPage] = useState(1);
  const [drawer, setDrawer] = useState(false);
  const [ready, setReady] = useState(false);
  const gridTop = useRef<HTMLDivElement>(null);

  // ---- read state from the URL on mount (and on back/forward) ----
  const syncFromUrl = useCallback(() => {
    const sp = new URLSearchParams(window.location.search);
    setSelSubs(fromCsv(sp.get("subs")));
    setSelBrands(fromCsv(sp.get("brands")));
    const pmin = Number(sp.get("pmin"));
    const pmax = Number(sp.get("pmax"));
    setPriceLo(Number.isFinite(pmin) && sp.get("pmin") ? Math.max(boundMin, pmin) : boundMin);
    setPriceHi(Number.isFinite(pmax) && sp.get("pmax") ? Math.min(boundMax, pmax) : boundMax);
    setSort(sp.get("sort") || "featured");
  }, [boundMin, boundMax]);

  useEffect(() => {
    syncFromUrl();
    setReady(true);
    const onPop = () => syncFromUrl();
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, [syncFromUrl]);

  // ---- write state to the URL (no navigation / no server refetch) ----
  useEffect(() => {
    if (!ready) return;
    const sp = new URLSearchParams();
    if (selSubs.length) sp.set("subs", csv(selSubs));
    if (selBrands.length) sp.set("brands", csv(selBrands));
    if (priceLo > boundMin) sp.set("pmin", String(priceLo));
    if (priceHi < boundMax) sp.set("pmax", String(priceHi));
    if (sort !== "featured") sp.set("sort", sort);
    const qs = sp.toString();
    const url = window.location.pathname + (qs ? `?${qs}` : "");
    window.history.replaceState(null, "", url);
    setPage(1);
  }, [ready, selSubs, selBrands, priceLo, priceHi, sort, boundMin, boundMax]);

  // ---- facet match helpers ----
  const matchSub = useCallback(
    (p: Product) => selSubs.length === 0 || (p.category ? selSubs.includes(p.category) : false),
    [selSubs]
  );
  const matchBrand = useCallback(
    (p: Product) => selBrands.length === 0 || selBrands.includes(p.brand),
    [selBrands]
  );
  const matchPrice = useCallback(
    (p: Product) => p.price >= priceLo && p.price <= priceHi,
    [priceLo, priceHi]
  );

  // ---- live facet counts (reflect the OTHER active facets) ----
  const subCounts = useMemo(() => {
    const m = new Map<string, number>();
    for (const p of products) {
      if (matchBrand(p) && matchPrice(p) && p.category) {
        m.set(p.category, (m.get(p.category) || 0) + 1);
      }
    }
    return m;
  }, [products, matchBrand, matchPrice]);

  const brandFacets = useMemo(() => {
    const m = new Map<string, number>();
    for (const p of products) {
      if (!p.brand) continue;
      if (matchSub(p) && matchPrice(p)) m.set(p.brand, (m.get(p.brand) || 0) + 1);
    }
    // keep any currently-selected brand visible even at count 0
    for (const b of selBrands) if (!m.has(b)) m.set(b, 0);
    return Array.from(m.entries())
      .map(([name, count]) => ({ name, count }))
      .sort((a, b) => a.name.localeCompare(b.name));
  }, [products, matchSub, matchPrice, selBrands]);

  const visibleSubFacets = useMemo(() => {
    if (!subFacets) return [];
    return subFacets
      .map((s) => ({ ...s, count: subCounts.get(s.slug) || 0 }))
      .filter((s) => s.count > 0 || selSubs.includes(s.slug))
      .sort((a, b) => a.name.localeCompare(b.name));
  }, [subFacets, subCounts, selSubs]);

  // ---- final filtered + sorted list ----
  const filtered = useMemo(() => {
    const list = products.filter((p) => matchSub(p) && matchBrand(p) && matchPrice(p));
    if (sort === "price-asc") list.sort((a, b) => a.price - b.price);
    else if (sort === "price-desc") list.sort((a, b) => b.price - a.price);
    else if (sort === "name") list.sort((a, b) => a.name.localeCompare(b.name));
    return list;
  }, [products, matchSub, matchBrand, matchPrice, sort]);

  const pages = Math.max(1, Math.ceil(filtered.length / PER));
  const current = Math.min(page, pages);
  const shown = filtered.slice((current - 1) * PER, current * PER);

  const activeCount =
    selSubs.length + selBrands.length + (priceLo > boundMin || priceHi < boundMax ? 1 : 0);

  function toggle(list: string[], set: (v: string[]) => void, v: string) {
    set(list.includes(v) ? list.filter((x) => x !== v) : [...list, v]);
  }
  function clearAll() {
    setSelSubs([]);
    setSelBrands([]);
    setPriceLo(boundMin);
    setPriceHi(boundMax);
    setSort("featured");
  }
  function goPage(n: number) {
    setPage(n);
    gridTop.current?.scrollIntoView({ behavior: "smooth", block: "start" });
  }

  const hasPrice = boundMax > boundMin;
  const pct = (v: number) => (hasPrice ? ((v - boundMin) / (boundMax - boundMin)) * 100 : 0);

  // ---- filter panel (shared by sidebar + mobile drawer) ----
  const panel = (
    <div className="pb-filters-inner">
      <div className="pb-filters-head">
        <span>Filters</span>
        {activeCount > 0 && (
          <button type="button" className="pb-filters-clear" onClick={clearAll}>
            Clear all
          </button>
        )}
      </div>

      {subNav && (
        <div className="pb-facet">
          <div className="pb-facet-title">Categories</div>
          <ul className="pb-facet-nav">
            <li>
              <Link
                href={subNav.allHref}
                className={!subNav.activeSlug ? "is-active" : ""}
              >
                All {subNav.catName}
              </Link>
            </li>
            {subNav.items.map((s) => (
              <li key={s.slug}>
                <Link href={s.href} className={s.slug === subNav.activeSlug ? "is-active" : ""}>
                  {s.name}
                </Link>
              </li>
            ))}
          </ul>
        </div>
      )}

      {visibleSubFacets.length > 0 && (
        <div className="pb-facet">
          <div className="pb-facet-title">Subcategory</div>
          <ul className="pb-facet-list">
            {visibleSubFacets.map((s) => (
              <li key={s.slug}>
                <label className="pb-check">
                  <input
                    type="checkbox"
                    checked={selSubs.includes(s.slug)}
                    onChange={() => toggle(selSubs, setSelSubs, s.slug)}
                  />
                  <span className="pb-check-box" aria-hidden="true" />
                  <span className="pb-check-name">{s.name}</span>
                  <span className="pb-check-count">{s.count}</span>
                </label>
              </li>
            ))}
          </ul>
        </div>
      )}

      {brandFacets.length > 1 && (
        <div className="pb-facet">
          <div className="pb-facet-title">Brand</div>
          <ul className="pb-facet-list pb-facet-scroll">
            {brandFacets.map((b) => (
              <li key={b.name}>
                <label className="pb-check">
                  <input
                    type="checkbox"
                    checked={selBrands.includes(b.name)}
                    onChange={() => toggle(selBrands, setSelBrands, b.name)}
                  />
                  <span className="pb-check-box" aria-hidden="true" />
                  <span className="pb-check-name">{b.name}</span>
                  <span className="pb-check-count">{b.count}</span>
                </label>
              </li>
            ))}
          </ul>
        </div>
      )}

      {hasPrice && (
        <div className="pb-facet">
          <div className="pb-facet-title">Price (AED)</div>
          <div className="pb-price">
            <div className="pb-price-track">
              <div
                className="pb-price-fill"
                style={{ left: `${pct(priceLo)}%`, right: `${100 - pct(priceHi)}%` }}
              />
              <input
                type="range"
                min={boundMin}
                max={boundMax}
                value={priceLo}
                aria-label="Minimum price"
                onChange={(e) => setPriceLo(Math.min(Number(e.target.value), priceHi))}
              />
              <input
                type="range"
                min={boundMin}
                max={boundMax}
                value={priceHi}
                aria-label="Maximum price"
                onChange={(e) => setPriceHi(Math.max(Number(e.target.value), priceLo))}
              />
            </div>
            <div className="pb-price-inputs">
              <input
                type="number"
                min={boundMin}
                max={priceHi}
                value={priceLo}
                aria-label="Minimum price"
                onChange={(e) => {
                  const v = Number(e.target.value);
                  setPriceLo(Math.min(Math.max(boundMin, v || boundMin), priceHi));
                }}
              />
              <span>–</span>
              <input
                type="number"
                min={priceLo}
                max={boundMax}
                value={priceHi}
                aria-label="Maximum price"
                onChange={(e) => {
                  const v = Number(e.target.value);
                  setPriceHi(Math.max(Math.min(boundMax, v || boundMax), priceLo));
                }}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );

  return (
    <div className="pb-shell" ref={gridTop}>
      <div className="pb-catlayout">
        {/* Sidebar (desktop) */}
        <aside className="pb-filters">{panel}</aside>

        {/* Main column */}
        <div className="pb-catmain">
          <div className="pb-toolbar">
            <div className="pb-toolbar-left">
              <button
                type="button"
                className="pb-filtersbtn"
                onClick={() => setDrawer(true)}
                aria-haspopup="dialog"
              >
                <svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true">
                  <path
                    d="M3 5h14M6 10h8M9 15h2"
                    stroke="currentColor"
                    strokeWidth="1.6"
                    strokeLinecap="round"
                  />
                </svg>
                Filters{activeCount > 0 ? ` (${activeCount})` : ""}
              </button>
              <span className="pb-toolbar-count">
                {filtered.length} {filtered.length === 1 ? "product" : "products"}
              </span>
            </div>
            <label className="pb-sort">
              <span>Sort</span>
              <select aria-label="Sort products" value={sort} onChange={(e) => setSort(e.target.value)}>
                <option value="featured">Featured</option>
                <option value="price-asc">Price: low to high</option>
                <option value="price-desc">Price: high to low</option>
                <option value="name">Name: A–Z</option>
              </select>
            </label>
          </div>

          {/* Active filter pills */}
          {activeCount > 0 && (
            <div className="pb-activefilters">
              {selSubs.map((s) => {
                const f = subFacets?.find((x) => x.slug === s);
                return (
                  <button key={`s-${s}`} type="button" className="pb-tagpill" onClick={() => toggle(selSubs, setSelSubs, s)}>
                    {f?.name || s} <span aria-hidden="true">×</span>
                  </button>
                );
              })}
              {selBrands.map((b) => (
                <button key={`b-${b}`} type="button" className="pb-tagpill" onClick={() => toggle(selBrands, setSelBrands, b)}>
                  {b} <span aria-hidden="true">×</span>
                </button>
              ))}
              {(priceLo > boundMin || priceHi < boundMax) && (
                <button
                  type="button"
                  className="pb-tagpill"
                  onClick={() => {
                    setPriceLo(boundMin);
                    setPriceHi(boundMax);
                  }}
                >
                  AED {priceLo}–{priceHi} <span aria-hidden="true">×</span>
                </button>
              )}
              <button type="button" className="pb-tagpill is-clear" onClick={clearAll}>
                Clear all
              </button>
            </div>
          )}

          {shown.length ? (
            <div className="pb-grid">
              {shown.map((p) => (
                <div className="pb-grid-cell" key={p.id}>
                  <ProductCard p={p} />
                </div>
              ))}
            </div>
          ) : (
            <div className="pb-empty">
              <p>No products match these filters.</p>
              <button type="button" className="pb-btn pb-btn--ghost" onClick={clearAll}>
                Clear filters
              </button>
            </div>
          )}

          {pages > 1 && (
            <nav className="pb-pagination" aria-label="Pages">
              <button className="pb-page-btn" disabled={current <= 1} onClick={() => goPage(current - 1)}>
                ←
              </button>
              {Array.from({ length: pages }, (_, i) => i + 1)
                .filter((n) => n === 1 || n === pages || Math.abs(n - current) <= 1)
                .map((n, idx, arr) => (
                  <span key={n} style={{ display: "contents" }}>
                    {idx > 0 && n - arr[idx - 1] > 1 && <span className="pb-page-gap">…</span>}
                    <button
                      className={`pb-page-btn${n === current ? " is-active" : ""}`}
                      onClick={() => goPage(n)}
                    >
                      {n}
                    </button>
                  </span>
                ))}
              <button className="pb-page-btn" disabled={current >= pages} onClick={() => goPage(current + 1)}>
                →
              </button>
            </nav>
          )}
        </div>
      </div>

      {/* Mobile drawer */}
      <div className={`pb-drawer${drawer ? " is-open" : ""}`} role="dialog" aria-modal="true" aria-label="Filters">
        <div className="pb-drawer-backdrop" onClick={() => setDrawer(false)} />
        <div className="pb-drawer-panel">
          <div className="pb-drawer-top">
            <strong>Filters</strong>
            <button type="button" className="pb-drawer-close" aria-label="Close filters" onClick={() => setDrawer(false)}>
              ×
            </button>
          </div>
          <div className="pb-drawer-body">{panel}</div>
          <div className="pb-drawer-foot">
            <button type="button" className="pb-btn pb-btn--ghost" onClick={clearAll}>
              Clear
            </button>
            <button type="button" className="pb-btn pb-btn--primary" onClick={() => setDrawer(false)}>
              Show {filtered.length} {filtered.length === 1 ? "result" : "results"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
