// ── Receipt detail ────────────────────────────────────────────────────────────

function ReceiptDetail({ id }) {
  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 [showDeleteConfirm, setShowDeleteConfirm] = React.useState(false);
  const [deleteMatchItem, setDeleteMatchItem] = React.useState(null);
  const [scrollToItem, setScrollToItem] = React.useState(null);
  const [savingItem, setSavingItem] = React.useState(null);

  React.useEffect(() => {
    setData(null);
    fetch(`/api/receipts/${encodeURIComponent(id)}`)
      .then((r) => (r.ok ? r.json() : Promise.reject(r.status)))
      .then((d) => {
        setData(d);
      })
      .catch((e) => setError(String(e)));
  }, [id, refreshKey]);

  React.useEffect(() => {
    if (!data || !scrollToItem) return;
    const el = document.getElementById(`item-${CSS.escape(scrollToItem)}`);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "center" });
    setScrollToItem(null);
  }, [data, scrollToItem]);

  async function confirmDeleteReceipt() {
    const res = await fetch(`/api/receipts/${encodeURIComponent(id)}`, {
      method: "DELETE",
    });
    if (res.ok) {
      location.hash = "#/receipts";
    }
  }

  async function confirmDeleteMatch() {
    await fetch(
      `/api/match/${encodeURIComponent(data.chain)}/${encodeURIComponent(deleteMatchItem)}`,
      { method: "DELETE" },
    );
    setDeleteMatchItem(null);
    setRefreshKey((k) => k + 1);
  }

  async function handleMatchSaved(itemName) {
    try {
      const d = await fetch(`/api/receipts/${encodeURIComponent(id)}`).then(
        (r) => r.json(),
      );
      setData((prev) => ({ ...prev, items: d.items }));
      setScrollToItem(itemName);
    } catch (e) {
      setRefreshKey((k) => k + 1);
    }
    await new Promise((r) => setTimeout(r, 300));
    setSavingItem(null);
  }

  function deleteMatch(itemName) {
    setDeleteMatchItem(itemName);
  }

  const colors = useChainColors();

  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 scontrino…
      </p>
    );

  const { r, chain, items, mongo_ok, brave_ok, source } = data;
  const store = r.store_address || r.store_name || "Sconosciuto";
  const { score_avg: scoreAvg, scored_count: scoredCount } = r;
  const scoreMin =
    scoreAvg != null
      ? Math.min(
          ...items
            .map((i) => i.match?.mediterranean_score?.score)
            .filter((s) => s != null),
        )
      : null;

  return (
    <div>
      <a
        href="#/receipts"
        className="inline-flex items-center gap-1 text-[#2d7a3a] text-sm font-medium mb-4"
      >
        ← Tutti gli scontrini
      </a>

      {/* Receipt header card */}
      <div className="bg-white rounded-2xl shadow-sm p-4 mb-4 space-y-3">
        {/* Row 1: Chain · Store · Date */}
        <div className="grid grid-cols-3 gap-3">
          {[
            ["Catena", <ChainBadge chain={chain} colors={colors} />],
            ["Negozio", store],
            ["Data", `${r.date || "—"}${r.time ? "  " + r.time : ""}`],
          ].map(([label, value]) => (
            <div key={label}>
              <div className="text-xs text-gray-400 uppercase tracking-wide">
                {label}
              </div>
              <div className="font-semibold text-gray-900 text-sm mt-0.5">
                {value}
              </div>
            </div>
          ))}
        </div>

        {/* Row 2: Total · Payment · Items */}
        <div className="grid grid-cols-3 gap-3 pt-3 border-t border-gray-100">
          {[
            ["Totale", `€${fmt(r.total_eur)}`],
            ["Pagamento", r.payment_method || "—"],
            ["Articoli", r.item_count],
          ].map(([label, value]) => (
            <div key={label}>
              <div className="text-xs text-gray-400 uppercase tracking-wide">
                {label}
              </div>
              <div className="font-semibold text-gray-900 text-sm mt-0.5">
                {value}
              </div>
            </div>
          ))}
        </div>

        {/* Row 3: Score qualità */}
        {scoreAvg != null && (
          <div className="pt-3 border-t border-gray-100 flex flex-col items-center text-center">
            <div className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">
              Score qualità
              <span className="font-normal ml-1">
                ({Math.round((scoredCount / items.length) * 100)}% degli
                articoli)
              </span>
            </div>
            <div className="flex gap-6">
              <div className="flex flex-col items-center gap-1">
                <div className="flex items-center gap-1">
                  <span
                    className="inline-flex items-center justify-center w-8 h-8 rounded-full text-sm font-bold text-white"
                    style={{ background: mediterraneanScoreColor(scoreAvg) }}
                  >
                    {scoreAvg}
                  </span>
                  <span className="text-xs text-gray-500">/100</span>
                </div>
                <div className="text-xs text-gray-400">Score medio</div>
              </div>
              <div className="flex flex-col items-center gap-1">
                <div className="flex items-center gap-1">
                  <span
                    className="inline-flex items-center justify-center w-8 h-8 rounded-full text-sm font-bold text-white"
                    style={{ background: mediterraneanScoreColor(scoreMin) }}
                  >
                    {scoreMin}
                  </span>
                  <span className="text-xs text-gray-500">/100</span>
                </div>
                <div className="text-xs text-gray-400">Prodotto peggiore</div>
              </div>
            </div>
          </div>
        )}

        {/* Row 4: badges (source / correction status) — only if present */}
        {(source === "ocr" || source === "manual" || r.user_corrected) && (
          <div className="flex gap-2 pt-3 border-t border-gray-100">
            {source === "ocr" && (
              <span className="text-xs bg-amber-100 text-amber-700 px-1.5 py-0.5 rounded font-medium">
                PDF / OCR
              </span>
            )}
            {source === "manual" && (
              <span className="text-xs bg-blue-100 text-blue-700 px-1.5 py-0.5 rounded font-medium">
                Manuale
              </span>
            )}
            {r.user_corrected && (
              <span className="text-xs bg-green-100 text-green-700 px-1.5 py-0.5 rounded font-medium">
                Corretto
              </span>
            )}
          </div>
        )}
        {/* Actions */}
        <div className="pt-3 border-t border-gray-100 flex justify-between items-center">
          <button
            onClick={() => setShowDeleteConfirm(true)}
            className="text-sm px-3 py-1.5 rounded-lg bg-red-50 text-red-600 font-medium hover:bg-red-100 transition-colors"
          >
            Elimina scontrino
          </button>
          {(source === "ocr" || source === "manual") && (
            <a
              href={`#/receipts/${id}/correct`}
              className="text-sm px-3 py-1.5 rounded-lg bg-amber-500 text-white font-medium hover:bg-amber-600 transition-colors"
            >
              {source === "manual"
                ? "Modifica scontrino"
                : "Correggi scontrino"}
            </a>
          )}
        </div>
      </div>

      {/* Items split: matched then unmatched */}
      {(() => {
        const matched = [];
        const unmatched = [];
        items.forEach((item, idx) => {
          if (
            (item.match?.off_found && !item.match?.suggested_from) ||
            item.match?.manual_info ||
            item.display_label
          ) {
            matched.push({ item, idx });
          } else {
            unmatched.push({ item, idx });
          }
        });

        return (
          <>
            {matched.length > 0 && (
              <div className="mb-5">
                <div className="flex items-center gap-2 mb-2 px-1">
                  <span className="text-xs font-bold text-gray-500 uppercase tracking-wider">
                    Abbinati
                  </span>
                  <span className="text-xs text-gray-300">
                    ({matched.length})
                  </span>
                </div>
                <div className="space-y-2">
                  {matched.map(({ item, idx }) => (
                    <Item
                      key={item.name + idx}
                      item={item}
                      idx={idx}
                      chain={chain}
                      receiptId={id}
                      mongo_ok={mongo_ok}
                      brave_ok={brave_ok}
                      expandedItem={expandedItem}
                      setExpandedItem={setExpandedItem}
                      deleteMatch={deleteMatch}
                      onMatchSaved={handleMatchSaved}
                      onSaved={(name) => setScrollToItem(name)}
                      savingItem={savingItem}
                      setSavingItem={setSavingItem}
                    />
                  ))}
                </div>
              </div>
            )}
            {unmatched.length > 0 && (
              <div className="mb-5">
                <div className="flex items-center gap-2 mb-2 px-1">
                  <span className="text-xs font-bold text-gray-500 uppercase tracking-wider">
                    Non abbinati
                  </span>
                  <span className="text-xs text-gray-300">
                    ({unmatched.length})
                  </span>
                </div>
                <div className="space-y-2">
                  {unmatched.map(({ item, idx }) => (
                    <Item
                      key={item.name + idx}
                      item={item}
                      idx={idx}
                      chain={chain}
                      receiptId={id}
                      mongo_ok={mongo_ok}
                      brave_ok={brave_ok}
                      expandedItem={expandedItem}
                      setExpandedItem={setExpandedItem}
                      deleteMatch={deleteMatch}
                      onMatchSaved={handleMatchSaved}
                      onSaved={(name) => setScrollToItem(name)}
                      savingItem={savingItem}
                      setSavingItem={setSavingItem}
                    />
                  ))}
                </div>
              </div>
            )}
          </>
        );
      })()}

      {showDeleteConfirm && (
        <ConfirmDialog
          title="Elimina scontrino"
          message="Verrà rimosso lo scontrino dal database. Il file PDF non verrà eliminato."
          confirmLabel="Elimina"
          danger
          onConfirm={confirmDeleteReceipt}
          onCancel={() => setShowDeleteConfirm(false)}
        />
      )}

      {deleteMatchItem && (
        <ConfirmDialog
          title="Rimuovi abbinamento"
          message={`Rimuovere l'abbinamento per: ${deleteMatchItem}?`}
          confirmLabel="Rimuovi"
          danger
          onConfirm={confirmDeleteMatch}
          onCancel={() => setDeleteMatchItem(null)}
        />
      )}
    </div>
  );
}
