"use client";

/**
 * The product catalogue on /global-agriculture (API reference: "How products work
 * (website)"). Same markup and classes as the designed catalogue; the products, the
 * filter options and their counts come from GET /public/products.
 *
 * - The server renders the first, unfiltered page (`initial`), so the page stays static.
 *   Filters live in the page URL (?category=…&origin=IR,ES…) so filtered pages can be
 *   shared; the browser fetches the matching products through /api/v1.
 * - Several values of one filter = OR, different filters = AND (done by the API). Each
 *   count already takes the other filters into account; options with no result are
 *   disabled.
 * - Until the API has a published product (or when it can't be reached) the designed
 *   catalogue is shown instead (StaticCatalog).
 */
import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type ChangeEvent, type ReactNode } from "react";
import type { ProductCatalogContent } from "@/app/(site)/_lib/pageContent";
import { NO_FILTERS, PAGE_SIZE, VOLUMES, filtersFromSearch, hasFilters, productQuery, type CatalogFilters, type ProductList } from "@/app/(site)/_lib/products";
import { StaticCatalog } from "../pages/global-agriculture/StaticCatalog";
import { ProductCardItem } from "./ProductCardItem";

/** Filter lists longer than this show "See More". */
const SHORT_LIST = 6;
const LANG = "en";

/* The page URL's query string is the filter state (shareable links). */
const urlListeners = new Set<() => void>();
function subscribeUrl(cb: () => void) {
  urlListeners.add(cb);
  addEventListener("popstate", cb);
  return () => {
    urlListeners.delete(cb);
    removeEventListener("popstate", cb);
  };
}
const urlSearch = () => window.location.search;
/** On the server (and while hydrating) there are no filters: the page is static. */
const serverSearch = () => "";
function setUrlQuery(qs: string) {
  window.history.replaceState(window.history.state, "", `${window.location.pathname}${qs ? `?${qs}` : ""}${window.location.hash}`);
  urlListeners.forEach((l) => l());
}

type Props = {
  c: ProductCatalogContent;
  /** First page without filters, from the server. null: the API couldn't be reached. undefined: load it here (admin preview). */
  initial?: ProductList | null;
};

export function ProductCatalog({ c, initial }: Props) {
  const filters = filtersFromSearch(useSyncExternalStore(subscribeUrl, urlSearch, serverSearch));
  const query = productQuery(filters);
  // Lists fetched in the browser, per query string; `latest` stays shown while the next one loads.
  const [results, setResults] = useState<{ byQuery: Record<string, ProductList>; failed: Record<string, true>; latest?: ProductList }>({ byQuery: {}, failed: {} });
  const fromServer = query === "" && initial !== undefined;
  const loading = !fromServer && !(query in results.byQuery) && !(query in results.failed);
  const data = fromServer ? initial : (results.byQuery[query] ?? results.latest ?? initial ?? null);
  // The catalogue exists once the API has at least one product (then even an empty filter result is shown as such).
  const exists = useMemo(() => (initial?.pagination.total ?? 0) > 0 || Object.values(results.byQuery).some((r) => r.pagination.total > 0), [initial, results.byQuery]);
  const [typed, setTyped] = useState<string | null>(null);
  const searchText = typed ?? filters.q;
  const [moreOrigins, setMoreOrigins] = useState(false);
  const [moreCerts, setMoreCerts] = useState(false);
  const sectionRef = useRef<HTMLElement>(null);

  // Fetch the products for the URL's filters (not needed for the server's unfiltered first page).
  useEffect(() => {
    if (!loading) return;
    const ctl = new AbortController();
    fetch(`/api/v1/public/products?lang=${LANG}&limit=${PAGE_SIZE}${query ? `&${query}` : ""}`, { signal: ctl.signal, headers: { Accept: "application/json" } })
      .then(async (res) => {
        if (!res.ok) throw new Error(String(res.status));
        const next = ((await res.json()) as { data: ProductList }).data;
        setResults((r) => ({ ...r, byQuery: { ...r.byQuery, [query]: next }, latest: next }));
      })
      .catch((e: Error) => {
        if (e.name === "AbortError") return;
        console.warn("[catalog] could not load products:", e);
        setResults((r) => ({ ...r, failed: { ...r.failed, [query]: true } }));
      });
    return () => ctl.abort();
  }, [loading, query]);

  const apply = (next: CatalogFilters, { scroll = false } = {}) => {
    setUrlQuery(productQuery(next));
    if (scroll) sectionRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
  };
  // Any filter change goes back to page 1.
  const set = (patch: Partial<CatalogFilters>) => apply({ ...filters, ...patch, page: 1 });
  const toggle = (key: "category" | "origin" | "certification", value: string) => (e: ChangeEvent<HTMLInputElement>) =>
    set({ [key]: e.target.checked ? [...filters[key], value] : filters[key].filter((v) => v !== value) });

  // Search: after a pause; 2+ characters (or cleared).
  useEffect(() => {
    if (typed === null) return;
    const t = setTimeout(() => {
      const q = typed.trim();
      if (q.length === 1 || q === filters.q) return;
      apply({ ...filters, q, page: 1 });
    }, 350);
    return () => clearTimeout(t);
    // eslint-disable-next-line react-hooks/exhaustive-deps -- runs on typing only
  }, [typed]);

  if (!exists || !data) return <StaticCatalog c={c} />;

  const { facets, items, pagination } = data;
  const farmingCount = (v: string) => facets.farming.find((f) => f.value === v)?.count ?? 0;
  const volumeCount = (v: string) => facets.volume.find((f) => f.value === v)?.count ?? 0;
  const allFarming = facets.farming.reduce((n, f) => n + f.count, 0);
  /** First SHORT_LIST options, plus any picked one beyond them, unless expanded. */
  const short = <T,>(list: T[], picked: (x: T) => boolean, expanded: boolean) => (expanded ? list : list.filter((x, i) => i < SHORT_LIST || picked(x)));

  const clear = () => {
    setTyped(null);
    apply(NO_FILTERS);
  };

  return (
    <section ref={sectionRef} className="bg-white pb-12 md:pb-16 lg:pb-20">
      <div className="w-full max-w-[1180px] mx-auto px-6">
        <div className="catalog-layout">
          <button type="button" className="catalog-filter-toggle" id="catalog-filter-toggle" aria-expanded="false" aria-controls="catalog-sidebar">
            {" "}
            <svg viewBox="0 0 20 20" fill="none" aria-hidden="true">
              <path d="M3 5h14M3 10h14M3 15h14" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"></path>
            </svg>{" "}
            {c.filtersLabel}{" "}
          </button>{" "}
          {/* SIDEBAR FILTERS */}{" "}
          <aside className="catalog-sidebar" id="catalog-sidebar" aria-label="Product filters">
            <div className="catalog-search">
              <svg className="catalog-search-icon" viewBox="0 0 20 20" fill="none" aria-hidden="true">
                <circle cx="9" cy="9" r="5.5" stroke="currentColor" strokeWidth="1.6"></circle>
                <path d="M13.5 13.5L17 17" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"></path>
              </svg>{" "}
              <input type="search" placeholder={c.searchPlaceholder} aria-label="Search products" maxLength={80} value={searchText} onChange={(e) => setTyped(e.target.value)} />
            </div>
            {facets.categories.length > 0 && (
              <div className="catalog-category-block">
                <h3 className="catalog-filter-heading">{c.filterHeadings.category}</h3>
                {facets.categories.map((g, gi) => (
                  <details key={g.slug} className="catalog-filter-group" open={gi === 0 || g.children.some((ch) => filters.category.includes(ch.slug))}>
                    <summary>{g.name}</summary>{" "}
                    <div className="catalog-filter-list">
                      {g.children.map((ch) => (
                        <Option key={ch.slug} type="checkbox" checked={filters.category.includes(ch.slug)} count={ch.count} onChange={toggle("category", ch.slug)}>
                          {ch.name}
                        </Option>
                      ))}
                    </div>
                  </details>
                ))}
              </div>
            )}
            {facets.origin.length > 0 && (
              <div className="catalog-filter-group">
                <h3 className="text-[14px] font-bold text-ink mb-3">{c.filterHeadings.originCountry}</h3>
                <div className="catalog-filter-list">
                  {short(facets.origin, (o) => filters.origin.includes(o.code), moreOrigins).map((o) => (
                    <Option key={o.code} type="checkbox" checked={filters.origin.includes(o.code)} count={o.count} onChange={toggle("origin", o.code)}>
                      {o.name}
                    </Option>
                  ))}
                </div>
                {facets.origin.length > SHORT_LIST && !moreOrigins && <SeeMore label={c.seeMoreLabel} onClick={() => setMoreOrigins(true)} />}
              </div>
            )}
            <div className="catalog-filter-group">
              <h3 className="text-[14px] font-bold text-ink mb-3">{c.filterHeadings.productType}</h3>
              <div className="catalog-filter-list">
                <Option type="radio" name="product-type" checked={!filters.farming} count={allFarming} onChange={() => set({ farming: "" })}>
                  {c.productTypeLabels.all}
                </Option>
                <Option type="radio" name="product-type" checked={filters.farming === "organic"} count={farmingCount("organic")} onChange={() => set({ farming: "organic" })}>
                  {c.productTypeLabels.organic}
                </Option>
                <Option type="radio" name="product-type" checked={filters.farming === "conventional"} count={farmingCount("conventional")} onChange={() => set({ farming: "conventional" })}>
                  {c.productTypeLabels.conventional}
                </Option>
              </div>
            </div>
            <div className="catalog-filter-group">
              <h3 className="text-[14px] font-bold text-ink mb-3">{c.filterHeadings.volume}</h3>
              <div className="catalog-filter-list">
                {VOLUMES.map(([value, label]) => (
                  <Option
                    key={value}
                    type="radio"
                    name="volume"
                    checked={filters.volume === value}
                    count={volumeCount(value)}
                    onChange={() => set({ volume: value })}
                    // A radio can't be unticked: clicking the picked range again clears it.
                    onClick={() => filters.volume === value && set({ volume: "" })}
                  >
                    {c.volumeLabels[label]}
                  </Option>
                ))}
              </div>
            </div>
            {facets.certifications.length > 0 && (
              <div className="catalog-filter-group">
                <h3 className="text-[14px] font-bold text-ink mb-3">{c.filterHeadings.certifications}</h3>
                <div className="catalog-filter-list">
                  {short(facets.certifications, (x) => filters.certification.includes(x.slug), moreCerts).map((x) => (
                    <Option key={x.slug} type="checkbox" checked={filters.certification.includes(x.slug)} count={x.count} onChange={toggle("certification", x.slug)}>
                      {x.name}
                    </Option>
                  ))}
                </div>
                {facets.certifications.length > SHORT_LIST && !moreCerts && <SeeMore label={c.seeMoreLabel} onClick={() => setMoreCerts(true)} />}
              </div>
            )}
          </aside>
          {/* PRODUCT GRID */}
          <div className="catalog-main" aria-busy={loading}>
            {items.length > 0 ? (
              <div className="product-catalog-grid" style={{ opacity: loading ? 0.55 : 1, transition: "opacity .15s ease" }}>
                {items.map((p) => (
                  <ProductCardItem key={p.id} p={p} pageLang={LANG} />
                ))}
              </div>
            ) : (
              <div className="py-16 text-center" role="status">
                <p className="text-[15px] text-[#2E2E2E]">{c.noResultsText || "No products match your filters."}</p>
                {hasFilters(filters) && (
                  <button type="button" className="catalog-filter-see-more" onClick={clear}>
                    Clear filters
                  </button>
                )}
              </div>
            )}
            {pagination.pages > 1 && <Pager page={pagination.page} pages={pagination.pages} onPage={(page) => apply({ ...filters, page }, { scroll: true })} />}
          </div>
        </div>
      </div>
    </section>
  );
}

/** A filter checkbox or radio. Options without results are disabled (unless picked, so they can be unticked). */
function Option({
  type,
  name,
  checked,
  count,
  onChange,
  onClick,
  children,
}: {
  type: "checkbox" | "radio";
  name?: string;
  checked: boolean;
  count: number;
  onChange: (e: ChangeEvent<HTMLInputElement>) => void;
  onClick?: () => void;
  children: ReactNode;
}) {
  const disabled = count === 0 && !checked;
  return (
    <label className="catalog-filter-item" style={disabled ? { opacity: 0.45, cursor: "default" } : undefined}>
      <input type={type} name={name} checked={checked} disabled={disabled} onChange={onChange} onClick={onClick} /> {children}
    </label>
  );
}

function SeeMore({ label, onClick }: { label: string; onClick: () => void }) {
  return (
    <a
      href="#"
      className="catalog-filter-see-more"
      onClick={(e) => {
        e.preventDefault();
        onClick();
      }}
    >
      {label}
    </a>
  );
}

/** Page numbers as designed: 1 2 3 … 10, around the current page. */
function pageList(page: number, pages: number): (number | "…")[] {
  const keep = new Set([1, pages, page - 1, page, page + 1]);
  if (page <= 3) [2, 3].forEach((p) => keep.add(p));
  if (page >= pages - 2) [pages - 2, pages - 1].forEach((p) => keep.add(p));
  const nums = [...keep].filter((p) => p >= 1 && p <= pages).sort((a, b) => a - b);
  const out: (number | "…")[] = [];
  nums.forEach((p, i) => {
    if (i > 0 && p - nums[i - 1] > 1) out.push("…");
    out.push(p);
  });
  return out;
}

const Arrow = ({ d }: { d: [string, string] }) => (
  <svg className="w-4 h-4" viewBox="0 0 16 16" fill="none" aria-hidden="true">
    <path d={d[0]} stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"></path>
    <path d={d[1]} stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"></path>
  </svg>
);

function Pager({ page, pages, onPage }: { page: number; pages: number; onPage: (p: number) => void }) {
  return (
    <nav className="pagination mt-12 flex items-center justify-center gap-2 flex-wrap" aria-label="Product pages">
      <button type="button" className="pagination-btn pagination-arrow" aria-label="Previous page" disabled={page <= 1} onClick={() => onPage(page - 1)}>
        {" "}
        <Arrow d={["M10 3L5 8l5 5", "M12 3L7 8l5 5"]} />{" "}
      </button>{" "}
      {pageList(page, pages).map((p, i) =>
        p === "…" ? (
          <span key={`e${i}`} className="pagination-ellipsis text-[#2E2E2E] px-1 select-none" aria-hidden="true">
            …
          </span>
        ) : (
          <button key={p} type="button" className={`pagination-btn${p === page ? " is-active" : ""}`} aria-current={p === page ? "page" : undefined} onClick={() => p !== page && onPage(p)}>
            {p}
          </button>
        ),
      )}{" "}
      <button type="button" className="pagination-btn pagination-arrow" aria-label="Next page" disabled={page >= pages} onClick={() => onPage(page + 1)}>
        {" "}
        <Arrow d={["M6 3l5 5-5 5", "M4 3l5 5-5 5"]} />{" "}
      </button>
    </nav>
  );
}
