// ── Predict Basket Page ───────────────────────────────────────────────────────

function ScoreBar({ score }) {
  const pct = Math.round(score * 100);
  const color = pct >= 70 ? "#16a34a" : pct >= 40 ? "#f59e0b" : "#d1d5db";
  return (
    <div className="flex items-center gap-2">
      <div className="flex-1 bg-gray-100 rounded-full h-1.5 overflow-hidden">
        <div
          className="h-1.5 rounded-full transition-all"
          style={{ width: `${pct}%`, backgroundColor: color }}
        />
      </div>
      <span className="text-xs text-gray-400 w-8 text-right">{pct}%</span>
    </div>
  );
}

function MetaItemCard({ p, chain, checked, onToggle, colors }) {
  const [expanded, setExpanded] = React.useState(false);
  const isAll = chain === "all";
  const hasVariants = isAll
    ? p.chain_variants && p.chain_variants.length > 0
    : p.variants && p.variants.length > 0;
  const noVariants = !hasVariants;

  return (
    <li className="py-2.5 border-b border-gray-50 last:border-0">
      <div className="flex items-start gap-3">
        <button
          onClick={onToggle}
          className={`w-5 h-5 rounded border-2 flex items-center justify-center shrink-0 mt-0.5 transition-colors ${
            checked
              ? "bg-green-500 border-green-500"
              : "border-gray-300 hover:border-green-400"
          }`}
        >
          {checked && (
            <svg
              className="w-3 h-3 text-white"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={3}
                d="M5 13l4 4L19 7"
              />
            </svg>
          )}
        </button>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <span
              className={`text-sm font-semibold ${
                checked ? "line-through text-gray-400" : "text-gray-800"
              }`}
            >
              {p.meta_item}
            </span>
            {!isAll && noVariants && (
              <span className="text-xs text-amber-500 bg-amber-50 px-1.5 py-0.5 rounded">
                non a {chain}
              </span>
            )}
          </div>
          <div className="flex items-center gap-3 mt-0.5 text-xs text-gray-400">
            <span>
              {p.total_qty} {p.total_qty === 1 ? "unità" : "unità"}
            </span>
            {p.avg_interval_days && (
              <span>ogni ~{Math.round(p.avg_interval_days)}g</span>
            )}
            <span>{p.days_since_last}g fa</span>
            {p.variant_count > 1 && <span>{p.variant_count} prodotti</span>}
          </div>
          <div className="mt-1">
            <ScoreBar score={p.score} />
          </div>

          {/* Chain-specific variants (single chain mode) */}
          {!isAll && hasVariants && (
            <div className="mt-1.5">
              {p.variants.length === 1 ? (
                <div className="text-xs text-gray-500">
                  <span className="font-medium">{p.variants[0].name}</span>
                  {p.variants[0].brand && (
                    <span className="text-gray-400">
                      {" "}
                      · {p.variants[0].brand}
                    </span>
                  )}
                </div>
              ) : (
                <>
                  <button
                    onClick={() => setExpanded(!expanded)}
                    className="text-xs text-[#2d7a3a] hover:underline flex items-center gap-1"
                  >
                    {expanded ? "Nascondi" : "Mostra"} {p.variants.length}{" "}
                    opzioni
                    <svg
                      className={`w-3 h-3 transition-transform ${expanded ? "rotate-180" : ""}`}
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M19 9l-7 7-7-7"
                      />
                    </svg>
                  </button>
                  {expanded && (
                    <ul className="mt-1 space-y-0.5 pl-1 border-l-2 border-green-100">
                      {p.variants.map((v) => (
                        <li
                          key={v.barcode}
                          className="text-xs text-gray-500 pl-2"
                        >
                          <span className="font-medium">{v.name}</span>
                          {v.brand && (
                            <span className="text-gray-400"> · {v.brand}</span>
                          )}
                        </li>
                      ))}
                    </ul>
                  )}
                </>
              )}
            </div>
          )}

          {/* All-chains variants (grouped by chain) */}
          {isAll && hasVariants && (
            <div className="mt-1.5">
              <button
                onClick={() => setExpanded(!expanded)}
                className="text-xs text-[#2d7a3a] hover:underline flex items-center gap-1"
              >
                {expanded ? "Nascondi" : "Mostra"}{" "}
                {p.available_chains.length !== 1
                  ? `${p.available_chains.length} catene`
                  : "1 catena"}
                <svg
                  className={`w-3 h-3 transition-transform ${expanded ? "rotate-180" : ""}`}
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M19 9l-7 7-7-7"
                  />
                </svg>
              </button>
              {expanded && (
                <div className="mt-1.5 space-y-2">
                  {p.chain_variants.map((cv) => {
                    const color = (colors && colors[cv.chain]) || {
                      bg: "#f3f4f6",
                      text: "#374151",
                    };
                    return (
                      <div key={cv.chain}>
                        <div className="flex items-center gap-1.5 mb-0.5">
                          <span
                            className="px-1.5 py-0.5 rounded text-xs font-bold capitalize"
                            style={{
                              backgroundColor: color.bg,
                              color: color.text,
                            }}
                          >
                            {cv.chain}
                          </span>
                        </div>
                        <ul className="space-y-0.5 pl-1 border-l-2 border-green-100">
                          {cv.variants.map((v) => (
                            <li
                              key={v.barcode}
                              className="text-xs text-gray-500 pl-2"
                            >
                              <span className="font-medium">{v.name}</span>
                              {v.brand && (
                                <span className="text-gray-400">
                                  {" "}
                                  · {v.brand}
                                </span>
                              )}
                            </li>
                          ))}
                        </ul>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </li>
  );
}

function BasketPage() {
  const [chain, setChain] = React.useState("all");
  const [data, setData] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [newItem, setNewItem] = React.useState("");
  const [refreshKey, setRefreshKey] = React.useState(0);
  const [checkedItems, setCheckedItems] = React.useState({});
  const colors = useChainColors();

  // Load predictions
  React.useEffect(() => {
    setData(null);
    setError(null);
    fetch(`/api/predict-basket?chain=${encodeURIComponent(chain)}&limit=30`)
      .then((r) => (r.ok ? r.json() : Promise.reject(r.status)))
      .then((d) => {
        setData(d);
        setCheckedItems({});
      })
      .catch((e) => setError(String(e)));
  }, [chain, refreshKey]);

  async function addToList(e) {
    e.preventDefault();
    const text = newItem.trim();
    if (!text) return;
    await fetch("/api/shopping-list", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        item_text: text,
        chain: chain === "all" ? "" : chain,
      }),
    });
    setNewItem("");
    setRefreshKey((k) => k + 1);
  }

  async function removeFromList(id) {
    await fetch(`/api/shopping-list/${id}`, { method: "DELETE" });
    setRefreshKey((k) => k + 1);
  }

  function toggleCheck(key) {
    setCheckedItems((prev) => ({ ...prev, [key]: !prev[key] }));
  }

  const checkedCount = Object.values(checkedItems).filter(Boolean).length;

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold">Spesa</h1>
      </div>

      {error && (
        <div className="text-red-600 text-sm p-3 bg-red-50 rounded-lg">
          Errore di caricamento: {error}
        </div>
      )}

      {/* Shopping list — manual items */}
      <div className="bg-white rounded-xl shadow-sm p-4">
        <h2 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">
          Lista della spesa
        </h2>
        <form onSubmit={addToList} className="flex gap-2 mb-3">
          <input
            type="text"
            value={newItem}
            onChange={(e) => setNewItem(e.target.value)}
            placeholder="Aggiungi un articolo da ricordare…"
            className="flex-1 border border-gray-200 rounded-lg px-3 py-2 text-sm bg-gray-50 focus:outline-none focus:ring-2 focus:ring-green-400 focus:bg-white"
          />
          <button
            type="submit"
            className="px-4 py-2 bg-[#2d7a3a] text-white text-sm font-medium rounded-lg hover:bg-[#236b2f] transition-colors"
          >
            Aggiungi
          </button>
        </form>
        {data?.shopping_list?.length > 0 ? (
          <ul className="space-y-1">
            {data.shopping_list.map((s) => (
              <li key={s.id} className="flex items-center gap-3 py-1.5 group">
                <button
                  onClick={() => toggleCheck(`sl-${s.id}`)}
                  className={`w-5 h-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors ${
                    checkedItems[`sl-${s.id}`]
                      ? "bg-green-500 border-green-500"
                      : "border-gray-300 hover:border-green-400"
                  }`}
                >
                  {checkedItems[`sl-${s.id}`] && (
                    <svg
                      className="w-3 h-3 text-white"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={3}
                        d="M5 13l4 4L19 7"
                      />
                    </svg>
                  )}
                </button>
                <span
                  className={`flex-1 text-sm ${
                    checkedItems[`sl-${s.id}`]
                      ? "line-through text-gray-400"
                      : "text-gray-800"
                  }`}
                >
                  {s.item_text}
                </span>
                <button
                  onClick={() => removeFromList(s.id)}
                  className="text-gray-300 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity"
                  title="Rimuovi"
                >
                  <svg
                    className="w-4 h-4"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M6 18L18 6M6 6l12 12"
                    />
                  </svg>
                </button>
              </li>
            ))}
          </ul>
        ) : (
          <p className="text-xs text-gray-400">
            Nessun articolo — aggiungi cose che non vuoi dimenticare.
          </p>
        )}
      </div>

      {/* Predicted meta-items */}
      {!data ? (
        <div className="flex justify-center py-8 text-gray-400">
          Caricamento…
        </div>
      ) : data.predictions.length === 0 ? (
        <div className="bg-white rounded-xl shadow-sm p-6 text-center text-gray-400 text-sm">
          Nessuna previsione — servono almeno 3 acquisti negli ultimi 6 mesi per
          gli articoli abbinati.
        </div>
      ) : (
        <div className="bg-white rounded-xl shadow-sm p-4">
          <div className="flex items-center justify-between mb-1">
            <h2 className="text-sm font-semibold text-gray-500 uppercase tracking-wide">
              Probabilmente hai bisogno di
            </h2>
            {data?.chains && (
              <select
                value={chain}
                onChange={(e) => setChain(e.target.value)}
                className="text-sm border border-gray-200 rounded-lg px-3 py-1.5 bg-white text-gray-700 focus:outline-none focus:ring-2 focus:ring-green-400"
              >
                <option value="all">Qualsiasi negozio</option>
                {data.chains.map((c) => (
                  <option key={c} value={c}>
                    {c.charAt(0).toUpperCase() + c.slice(1)}
                  </option>
                ))}
              </select>
            )}
          </div>
          <p className="text-xs text-gray-400 mb-3">
            In base ai tuoi acquisti in tutte le catene.
            {chain !== "all" && (
              <>
                {" "}
                Mostrando ciò che è disponibile a{" "}
                <span className="capitalize font-medium">{chain}</span>.
              </>
            )}
          </p>
          <ul className="space-y-0.5">
            {data.predictions.map((p) => {
              const key = `meta-${p.meta_item}`;
              return (
                <MetaItemCard
                  key={p.meta_item}
                  p={p}
                  chain={chain}
                  checked={!!checkedItems[key]}
                  onToggle={() => toggleCheck(key)}
                  colors={colors}
                />
              );
            })}
          </ul>
          {checkedCount > 0 && (
            <div className="mt-4 pt-3 border-t border-gray-100 flex justify-between items-center">
              <span className="text-sm text-gray-500">
                {checkedCount}{" "}
                {checkedCount !== 1
                  ? "articoli selezionati"
                  : "articolo selezionato"}
              </span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
