// ── Receipt correction view ───────────────────────────────────────────────────

function ReceiptCorrect({ id }) {
  const [rawData, setRawData] = React.useState(null);
  const [form, setForm] = React.useState(null);
  const [chains, setChains] = React.useState([]);
  const storeNames = useStoreNames();
  const [error, setError] = React.useState(null);
  const [saveState, setSaveState] = React.useState("idle"); // idle|saving|saved|error
  const [saveError, setSaveError] = React.useState(null);
  const [mobileView, setMobileView] = React.useState("left"); // left|right
  const keyCounter = React.useRef(0);

  function cycleMobileView() {
    setMobileView((v) => (v === "left" ? "right" : "left"));
  }

  React.useEffect(() => {
    fetch("/api/chains")
      .then((r) => r.json())
      .then(({ chains }) => setChains(chains.map((c) => c.name)))
      .catch(() => {});
  }, []);

  React.useEffect(() => {
    setRawData(null);
    setForm(null);
    setError(null);
    fetch(`/api/receipts/${encodeURIComponent(id)}?raw=true`)
      .then((r) => (r.ok ? r.json() : Promise.reject(r.status)))
      .then(({ data }) => {
        setRawData(data);
        setForm({
          ...data,
          items: (data.items || []).map((item) => ({
            ...item,
            _key: ++keyCounter.current,
          })),
        });
      })
      .catch((e) => setError(String(e)));
  }, [id]);

  function setField(field, value) {
    setForm((f) => ({ ...f, [field]: value }));
  }

  function setItemField(key, field, value) {
    setForm((f) => ({
      ...f,
      items: f.items.map((item) =>
        item._key === key ? { ...item, [field]: value } : item,
      ),
    }));
  }

  function deleteItem(key) {
    setForm((f) => ({
      ...f,
      items: f.items.filter((item) => item._key !== key),
    }));
  }

  function addItem() {
    setForm((f) => ({
      ...f,
      items: [
        ...f.items,
        {
          _key: ++keyCounter.current,
          name: "",
          quantity: 1,
          amount_eur: 0,
          vat: "",
          vat_pct: null,
          amount_cents: 0,
          discount_eur: null,
        },
      ],
    }));
  }

  async function handleSave() {
    setSaveState("saving");
    setSaveError(null);
    // Clean up _key fields and recompute derived fields before sending
    const payload = {
      ...form,
      items: form.items.map(({ _key, ...item }) => {
        const eur = parseFloat(item.amount_eur) || 0;
        const vatPct =
          parseFloat(item.vat) ||
          (form.vat_legend && item.vat
            ? parseFloat(form.vat_legend[item.vat.toUpperCase()]) || null
            : null);
        const disc = item.discount_eur ? parseFloat(item.discount_eur) : null;
        return {
          ...item,
          amount_eur: eur,
          amount_cents: Math.round(eur * 100),
          vat_pct: vatPct,
          discount_eur: disc,
          discount_cents: disc ? Math.round(disc * 100) : undefined,
        };
      }),
      discount_cents: Math.round((parseFloat(form.discount_eur) || 0) * 100),
      total_cents: Math.round((parseFloat(form.total_eur) || 0) * 100),
    };
    try {
      const res = await fetch(`/api/receipts/${encodeURIComponent(id)}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      setSaveState("saved");
      setTimeout(() => setSaveState("idle"), 2000);
    } catch (e) {
      setSaveState("error");
      setSaveError(e.message);
    }
  }

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

  if (rawData.source !== "ocr" && rawData.source !== "manual") {
    return (
      <div className="p-6 text-center text-gray-500 text-sm">
        La modifica è disponibile solo per scontrini OCR e manuali.{" "}
        <a href={`#/receipts/${id}`} className="text-[#2d7a3a] font-medium">
          Torna allo scontrino
        </a>
      </div>
    );
  }

  const itemsSumCents = (form.items || []).reduce(
    (acc, item) => acc + Math.round((parseFloat(item.amount_eur) || 0) * 100),
    0,
  );
  const itemDiscountsCents = (form.items || []).reduce(
    (acc, item) => acc + Math.round((parseFloat(item.discount_eur) || 0) * 100),
    0,
  );
  const itemsSum = itemsSumCents / 100;
  const receiptDiscountCents = Math.round(
    (parseFloat(form.discount_eur) || 0) * 100,
  );
  const expectedTotalCents = itemsSumCents - receiptDiscountCents;
  const expectedTotal = expectedTotalCents / 100;
  const totalMismatch =
    Math.abs(
      expectedTotalCents - Math.round((parseFloat(form.total_eur) || 0) * 100),
    ) > 1;

  const isManual = rawData.source === "manual";

  return (
    <div className="flex flex-col md:flex-row h-screen overflow-hidden">
      {/* Left panel — editable form */}
      <div
        className={`${mobileView === "right" ? "hidden" : ""} md:block ${isManual ? "w-full max-w-lg mx-auto" : "md:w-1/2"} overflow-y-auto p-4 md:p-6 pb-6`}
      >
        <div className="flex items-center gap-3 mb-4">
          <a
            href={`#/receipts/${id}`}
            className="inline-flex items-center gap-1 text-[#2d7a3a] text-sm font-medium"
          >
            ← Indietro
          </a>
          <h1 className="text-base font-semibold text-gray-800">
            {isManual ? "Modifica scontrino" : "Correggi scontrino"}
          </h1>
          {rawData.user_corrected && (
            <span className="text-xs bg-green-100 text-green-700 px-1.5 py-0.5 rounded font-medium">
              Precedentemente corretto
            </span>
          )}
          {!isManual && (
            <button
              onClick={cycleMobileView}
              className="md:hidden ml-auto text-xs border border-gray-200 rounded-lg px-2.5 py-1 text-gray-500 bg-white"
            >
              {mobileView === "left" ? "PDF" : "Modulo"}
            </button>
          )}
        </div>

        {/* Header fields */}
        <div className="bg-white rounded-2xl shadow-sm p-4 mb-4 space-y-3">
          <h2 className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-2">
            Informazioni scontrino
          </h2>
          <datalist id="rc-store-names">
            {storeNames.map((n) => (
              <option key={n} value={n} />
            ))}
          </datalist>
          <datalist id="rc-payment">
            {PAYMENT_SUGGESTIONS.map((n) => (
              <option key={n} value={n} />
            ))}
          </datalist>
          {[
            ["Nome negozio", "store_name", "rc-store-names"],
            ["Indirizzo negozio", "store_address", null],
            ["Data (GG/MM/AAAA)", "date", null],
            ["Ora (HH:MM)", "time", null],
            ["Metodo di pagamento", "payment_method", "rc-payment"],
          ].map(([label, field, listId]) => (
            <div key={field}>
              <label className="block text-xs text-gray-400 mb-0.5">
                {label}
              </label>
              <input
                type="text"
                value={form[field] || ""}
                list={listId || undefined}
                onChange={(e) => setField(field, e.target.value)}
                className="w-full text-sm border border-gray-200 rounded-lg px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-amber-300"
              />
            </div>
          ))}
          <div>
            <label className="block text-xs text-gray-400 mb-0.5">Catena</label>
            <select
              value={form.chain || "unknown"}
              onChange={(e) => setField("chain", e.target.value)}
              className="w-full text-sm border border-gray-200 rounded-lg px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-amber-300 bg-white"
            >
              {chains.map((c) => (
                <option key={c} value={c}>
                  {c}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Items table */}
        <div className="bg-white rounded-2xl shadow-sm p-4 mb-4">
          <h2 className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3">
            Articoli
          </h2>
          {/* Column headers — desktop only */}
          <div className="hidden md:flex text-xs text-gray-400 uppercase mb-1 gap-2">
            <span className="flex-1 font-medium">Nome</span>
            <span className="w-12 text-right font-medium">Qtà</span>
            <span className="w-14 text-right font-medium">IVA</span>
            <span className="w-20 text-right font-medium">€</span>
            <span className="w-20 text-right font-medium">Sc.</span>
            <span className="w-6"></span>
          </div>
          <div className="space-y-2">
            {form.items.map((item) => (
              <div
                key={item._key}
                className="border-t border-gray-50 pt-2 flex flex-col md:flex-row md:items-center gap-1 md:gap-2"
              >
                {/* Row 1: name */}
                <input
                  type="text"
                  value={item.name}
                  onChange={(e) =>
                    setItemField(item._key, "name", e.target.value)
                  }
                  className="md:flex-1 w-full text-sm border border-gray-200 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-amber-300"
                  placeholder="Nome articolo"
                />
                {/* Row 2 on mobile: qty, vat, €, disc, delete */}
                <div className="flex items-end gap-1 md:contents">
                  <label className="flex-shrink-0 w-14 md:w-12">
                    <span className="md:hidden block text-xs text-gray-400 mb-0.5">
                      Qtà
                    </span>
                    <input
                      type="number"
                      value={item.quantity}
                      min="1"
                      onChange={(e) =>
                        setItemField(
                          item._key,
                          "quantity",
                          parseInt(e.target.value) || 1,
                        )
                      }
                      className="w-full text-sm border border-gray-200 rounded px-2 py-1 text-right focus:outline-none focus:ring-1 focus:ring-amber-300"
                    />
                  </label>
                  <label className="flex-shrink-0 w-14">
                    <span className="md:hidden block text-xs text-gray-400 mb-0.5">
                      IVA
                    </span>
                    <input
                      type="text"
                      value={item.vat || ""}
                      onChange={(e) =>
                        setItemField(item._key, "vat", e.target.value)
                      }
                      className="w-full text-sm border border-gray-200 rounded px-2 py-1 text-right focus:outline-none focus:ring-1 focus:ring-amber-300"
                      placeholder="4%"
                    />
                  </label>
                  <label className="flex-shrink-0 w-20">
                    <span className="md:hidden block text-xs text-gray-400 mb-0.5">
                      €
                    </span>
                    <input
                      type="text"
                      inputMode="decimal"
                      value={item.amount_eur}
                      onChange={(e) =>
                        setItemField(item._key, "amount_eur", e.target.value)
                      }
                      onBlur={(e) => {
                        const v = evalPrice(e.target.value);
                        if (v !== null)
                          setItemField(item._key, "amount_eur", v);
                      }}
                      className="w-full text-sm border border-gray-200 rounded px-2 py-1 text-right focus:outline-none focus:ring-1 focus:ring-amber-300"
                    />
                  </label>
                  <label className="flex-shrink-0 w-20">
                    <span className="md:hidden block text-xs text-gray-400 mb-0.5">
                      Sc.
                    </span>
                    <input
                      type="text"
                      inputMode="decimal"
                      value={item.discount_eur || ""}
                      onChange={(e) =>
                        setItemField(item._key, "discount_eur", e.target.value)
                      }
                      onBlur={(e) => {
                        const v = evalPrice(e.target.value);
                        setItemField(
                          item._key,
                          "discount_eur",
                          v !== null ? Math.abs(v) : null,
                        );
                      }}
                      className="w-full text-sm border border-gray-200 rounded px-2 py-1 text-right focus:outline-none focus:ring-1 focus:ring-amber-300"
                      placeholder="0"
                    />
                  </label>
                  <button
                    onClick={() => deleteItem(item._key)}
                    className="w-6 mb-0.5 text-gray-300 hover:text-red-400 transition-colors text-base leading-none flex-shrink-0"
                    title="Rimuovi articolo"
                  >
                    ×
                  </button>
                </div>
              </div>
            ))}
          </div>
          <button
            onClick={addItem}
            className="mt-3 text-xs text-amber-600 hover:text-amber-700 font-medium"
          >
            + Aggiungi articolo
          </button>
        </div>

        {/* VAT legend (only shown when present) */}
        {form.vat_legend && (
          <div className="bg-white rounded-2xl shadow-sm p-4 mb-4">
            <h2 className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3">
              Legenda IVA
            </h2>
            <div className="space-y-2">
              {Object.entries(form.vat_legend).map(([code, rate]) => (
                <div key={code} className="flex items-center gap-2">
                  <input
                    type="text"
                    value={code}
                    readOnly
                    className="w-16 text-sm border border-gray-200 rounded px-2 py-1 bg-gray-50 text-gray-500 text-center"
                  />
                  <span className="text-gray-400 text-sm">=</span>
                  <input
                    type="text"
                    value={rate}
                    onChange={(e) => {
                      const updated = {
                        ...form.vat_legend,
                        [code]: e.target.value,
                      };
                      setField("vat_legend", updated);
                    }}
                    className="w-20 text-sm border border-gray-200 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-amber-300"
                    placeholder="10%"
                  />
                  <button
                    onClick={() => {
                      const updated = { ...form.vat_legend };
                      delete updated[code];
                      setField(
                        "vat_legend",
                        Object.keys(updated).length ? updated : null,
                      );
                    }}
                    className="text-gray-300 hover:text-red-400 transition-colors text-base leading-none"
                    title="Rimuovi"
                  >
                    ×
                  </button>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Totals */}
        <div className="bg-white rounded-2xl shadow-sm p-4 mb-4 space-y-3">
          <h2 className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-2">
            Totali
          </h2>
          <div className="flex items-center justify-between text-sm text-gray-500">
            <span>Totale articoli</span>
            <span className="font-medium text-gray-700">
              €{itemsSum.toFixed(2)}
            </span>
          </div>
          <div className="flex items-center justify-between text-sm text-gray-500">
            <span>Sconti per articolo</span>
            <span className="font-medium text-gray-700">
              €{(itemDiscountsCents / 100).toFixed(2)}
            </span>
          </div>
          <div>
            <label className="block text-xs text-gray-400 mb-0.5">
              Sconto totale (€)
            </label>
            <input
              type="text"
              inputMode="decimal"
              value={form.discount_eur || 0}
              onChange={(e) => setField("discount_eur", e.target.value)}
              onBlur={(e) => {
                const v = evalPrice(e.target.value);
                if (v !== null) setField("discount_eur", Math.abs(v));
              }}
              className="w-full text-sm border border-gray-200 rounded-lg px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-amber-300"
            />
          </div>
          <div>
            <label className="block text-xs text-gray-400 mb-0.5">
              Totale (€)
            </label>
            <input
              type="text"
              inputMode="decimal"
              value={form.total_eur || 0}
              onChange={(e) => setField("total_eur", e.target.value)}
              onBlur={(e) => {
                const v = evalPrice(e.target.value);
                if (v !== null) setField("total_eur", v);
              }}
              className="w-full text-sm border border-gray-200 rounded-lg px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-amber-300"
            />
          </div>
          {totalMismatch && (
            <p className="text-xs text-amber-600 bg-amber-50 rounded-lg px-3 py-2">
              Totale atteso €{expectedTotal.toFixed(2)} (articoli − sconti).
              Aggiusta manualmente.
            </p>
          )}
        </div>

        {/* Save button */}
        <button
          onClick={handleSave}
          disabled={saveState === "saving"}
          className={`w-full py-3 rounded-xl text-white font-semibold text-sm transition-colors ${
            saveState === "saved"
              ? "bg-green-500"
              : saveState === "saving"
                ? "bg-amber-300 cursor-not-allowed"
                : "bg-amber-500 hover:bg-amber-600"
          }`}
        >
          {saveState === "saving"
            ? "Salvataggio…"
            : saveState === "saved"
              ? "Salvato ✓"
              : "Salva correzioni"}
        </button>
        {saveState === "error" && (
          <p className="mt-2 text-xs text-red-500 text-center">
            {saveError || "Salvataggio fallito"}
          </p>
        )}
      </div>

      {/* Right panel — PDF viewer (OCR only) */}
      {!isManual && (
        <div
          className={`${mobileView === "left" ? "hidden" : ""} ${mobileView === "right" ? "flex-1 flex flex-col" : "min-h-[300px]"} md:flex-none md:block md:w-1/2 md:min-h-0 md:h-screen md:sticky md:top-0 border-t md:border-t-0 md:border-l border-gray-200 relative`}
        >
          <button
            onClick={cycleMobileView}
            className="md:hidden absolute top-2 right-2 z-10 text-xs border border-gray-200 rounded-lg px-2.5 py-1 text-gray-600 bg-white shadow-sm"
          >
            ← Modulo
          </button>
          <iframe
            src={`/api/pdf/${encodeURIComponent(id)}`}
            className="w-full h-full flex-1 border-0"
            title="PDF scontrino"
            style={{ minHeight: mobileView === "right" ? "0" : "300px" }}
          />
        </div>
      )}
    </div>
  );
}
