// ── Items page ────────────────────────────────────────────────────────────────

const ITEMS_PAGE_SIZE = 50;

function ItemsPage() {
  const [chain, setChain] = React.useState("all");
  const [data, setData] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [refreshKey, setRefreshKey] = React.useState(0);
  const [expandedItem, setExpandedItem] = React.useState(null);
  const [page, setPage] = React.useState(0);
  const [scanning, setScanning] = React.useState(false);
  const videoRef = React.useRef(null);
  const readerRef = React.useRef(null);
  const colors = useChainColors();

  // Start/stop camera with ZXing for barcode scan
  React.useEffect(() => {
    if (!scanning) return;
    if (!videoRef.current) return;
    const reader = new ZXing.BrowserMultiFormatReader();
    readerRef.current = reader;
    reader
      .decodeFromVideoDevice(undefined, videoRef.current, (result) => {
        if (!result) return;
        const text = result.getText();
        reader.reset();
        readerRef.current = null;
        setScanning(false);
        window.location.hash = `#/item/${encodeURIComponent(text)}`;
      })
      .catch(() => setScanning(false));
    return () => {
      reader.reset();
      readerRef.current = null;
    };
  }, [scanning]);

  function stopScan() {
    readerRef.current?.reset();
    readerRef.current = null;
    setScanning(false);
  }

  React.useEffect(() => {
    setData(null);
    fetch(
      `/api/items?chain=${encodeURIComponent(chain)}&page=${page}&page_size=${ITEMS_PAGE_SIZE}`,
    )
      .then((r) => (r.ok ? r.json() : Promise.reject(r.status)))
      .then((d) => {
        setData(d);
        if (chain !== "all" && !d.chains.includes(chain)) setChain("all");
      })
      .catch((e) => setError(String(e)));
  }, [chain, page, refreshKey]);

  async function deleteMatch(itemName, itemChain) {
    const c = itemChain || chain;
    if (!confirm(`Rimuovere l'abbinamento per: ${itemName}?`)) return;
    await fetch(
      `/api/match/${encodeURIComponent(c)}/${encodeURIComponent(itemName)}`,
      { method: "DELETE" },
    );
    setRefreshKey((k) => k + 1);
  }

  if (error) return <p className="text-sm text-red-500 p-4">Errore: {error}</p>;
  if (!data)
    return (
      <p className="text-sm text-gray-400 p-8 text-center">
        Caricamento prodotti…
      </p>
    );

  const { items, total_count, chains, mongo_ok } = data;
  const visibleItems = items;
  const totalPages = Math.ceil(total_count / ITEMS_PAGE_SIZE);

  return (
    <div>
      <div className="flex items-center justify-between mb-3">
        <h1 className="text-xl font-bold">
          Tutti i prodotti{" "}
          <span className="text-sm text-gray-400 font-normal">
            ({total_count})
          </span>
        </h1>
        <button
          onClick={scanning ? stopScan : () => setScanning(true)}
          className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors ${
            scanning
              ? "bg-red-50 border-red-200 text-red-600"
              : "bg-white border-gray-200 text-gray-600 active:bg-gray-50"
          }`}
          title={scanning ? "Interrompi scansione" : "Scansiona un prodotto"}
        >
          <svg
            className="w-4 h-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M4 7V5a1 1 0 011-1h2M4 17v2a1 1 0 001 1h2M20 7V5a1 1 0 00-1-1h-2M20 17v2a1 1 0 01-1 1h-2M8 12h8"
            />
          </svg>
          {scanning ? "Annulla" : "Scansiona"}
        </button>
      </div>

      {/* Camera viewfinder */}
      {scanning && (
        <div className="mb-4 relative rounded-xl overflow-hidden bg-black">
          <video
            ref={videoRef}
            className="w-full"
            style={{ maxHeight: 240 }}
            playsInline
            muted
          />
          <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
            <div
              className="border-2 border-white/70 rounded-lg"
              style={{ width: 220, height: 90 }}
            />
          </div>
          <div className="absolute bottom-2 inset-x-0 text-center text-white/70 text-xs">
            Inquadra il codice a barre per vedere la scheda prodotto
          </div>
        </div>
      )}

      {/* Chain filter pills */}
      <div className="flex flex-wrap gap-1.5 mb-4">
        {["all", ...chains].map((c) => {
          const color =
            c === "all"
              ? null
              : (colors && colors[c]) || _CHAIN_COLORS_FALLBACK;
          const active = chain === c;
          return (
            <button
              key={c}
              onClick={() => {
                setChain(c);
                setPage(0);
              }}
              style={
                active && color
                  ? { backgroundColor: color.bg, color: color.text }
                  : {}
              }
              className={`px-3 py-1 rounded-full text-sm font-medium transition-colors capitalize
                ${
                  active
                    ? color
                      ? ""
                      : "bg-gray-800 text-white"
                    : "bg-white text-gray-600 hover:bg-gray-100"
                }`}
            >
              {c === "all" ? "Tutti" : c}
            </button>
          );
        })}
      </div>

      {/* Empty state */}
      {visibleItems.length === 0 && (
        <div className="text-center py-16 text-gray-400">
          <p className="text-base font-medium text-gray-500 mb-1">
            Nessun prodotto abbinato
          </p>
          <p className="text-sm">
            Apri uno scontrino e abbina gli articoli ai prodotti per vederli
            qui.
          </p>
        </div>
      )}

      {/* Items list */}
      <div className="space-y-2">
        {visibleItems.map((item, idx) => (
          <Item
            key={(item.chain || chain) + item.name + idx}
            item={item}
            idx={page * ITEMS_PAGE_SIZE + idx}
            chain={item.chain || item.match?.chain || chain}
            mongo_ok={mongo_ok}
            expandedItem={expandedItem}
            setExpandedItem={setExpandedItem}
            deleteMatch={(name) =>
              deleteMatch(name, item.chain || item.match?.chain)
            }
            setRefreshKey={setRefreshKey}
            isItemsPage={true}
          />
        ))}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between mt-4 px-1">
          <button
            disabled={page === 0}
            onClick={() => setPage((p) => p - 1)}
            className="px-3 py-1.5 text-sm font-medium rounded-lg bg-white border border-gray-200 text-gray-600 disabled:opacity-30 active:bg-gray-50"
          >
            ← Prec
          </button>
          <span className="text-xs text-gray-400">
            {page + 1} / {totalPages}
          </span>
          <button
            disabled={page >= totalPages - 1}
            onClick={() => setPage((p) => p + 1)}
            className="px-3 py-1.5 text-sm font-medium rounded-lg bg-white border border-gray-200 text-gray-600 disabled:opacity-30 active:bg-gray-50"
          >
            Succ →
          </button>
        </div>
      )}
    </div>
  );
}
