// ── Manual receipt creation ────────────────────────────────────────────────────

function ManualReceiptCreate() {
  const [mode, setMode] = React.useState("upload"); // upload|manual
  const [chains, setChains] = React.useState([]);
  const storeNames = useStoreNames();
  const [saveState, setSaveState] = React.useState("idle"); // idle|saving|error
  const [saveError, setSaveError] = React.useState(null);
  const keyCounter = React.useRef(0);

  const [form, setForm] = React.useState(() => ({
    store_name: "",
    store_address: "",
    date: todayDMY(),
    time: nowHM(),
    payment_method: "",
    chain: "unknown",
    items: [{ _key: 1, name: "", amount_eur: "" }],
    total_eur: "",
  }));

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

  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 addItem() {
    setForm((f) => ({
      ...f,
      items: [
        ...f.items,
        { _key: ++keyCounter.current, name: "", amount_eur: "" },
      ],
    }));
  }

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

  const itemsSumCents = (form.items || []).reduce(
    (acc, item) => acc + Math.round((parseFloat(item.amount_eur) || 0) * 100),
    0,
  );
  const itemsSum = itemsSumCents / 100;

  const totalCents = Math.round((parseFloat(form.total_eur) || 0) * 100);
  const totalMismatch =
    form.total_eur !== "" && Math.abs(totalCents - itemsSumCents) > 1;

  async function handleSave() {
    setSaveState("saving");
    setSaveError(null);

    const items = form.items
      .filter((item) => item.name.trim())
      .map(({ _key, ...item }) => {
        const eur = parseFloat(item.amount_eur) || 0;
        return {
          name: item.name.trim(),
          amount_eur: eur,
          amount_cents: Math.round(eur * 100),
        };
      });

    const total = parseFloat(form.total_eur);
    const effectiveTotal = isNaN(total) ? itemsSum : total;

    const payload = {
      source: "manual",
      chain: form.chain || "unknown",
      store_name: form.store_name.trim() || null,
      store_address: form.store_address.trim() || null,
      date: form.date.trim(),
      time: form.time.trim(),
      payment_method: form.payment_method.trim() || null,
      items,
      item_count: items.length,
      total_eur: effectiveTotal,
      total_cents: Math.round(effectiveTotal * 100),
    };

    try {
      const res = await fetch("/api/receipts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const detail = await res.json().catch(() => ({}));
        throw new Error(detail.detail || `HTTP ${res.status}`);
      }
      const { id } = await res.json();
      window.location.hash = `#/receipts/${id}`;
    } catch (e) {
      setSaveState("error");
      setSaveError(e.message);
    }
  }

  return (
    <div className="max-w-lg mx-auto">
      <div className="flex items-center gap-3 mb-4">
        <a
          href="#/receipts"
          className="inline-flex items-center gap-1 text-[#2d7a3a] text-sm font-medium"
        >
          ← Indietro
        </a>
        <h1 className="text-base font-semibold text-gray-800">
          Aggiungi scontrino
        </h1>
      </div>

      <div className="flex gap-2 mb-4">
        <button
          onClick={() => setMode("upload")}
          className={`flex-1 py-2 rounded-lg text-sm font-medium transition-colors ${
            mode === "upload"
              ? "bg-[#2d7a3a] text-white"
              : "bg-white text-gray-600 border border-gray-200"
          }`}
        >
          Carica PDF
        </button>
        <button
          onClick={() => setMode("manual")}
          className={`flex-1 py-2 rounded-lg text-sm font-medium transition-colors ${
            mode === "manual"
              ? "bg-[#2d7a3a] text-white"
              : "bg-white text-gray-600 border border-gray-200"
          }`}
        >
          Inserisci manualmente
        </button>
      </div>

      {mode === "upload" && (
        <UploadPdf
          onUploaded={(id) => {
            if (id) window.location.hash = `#/receipts/${id}`;
          }}
        />
      )}

      {mode === "manual" && (
        <>
          <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="dl-store-names">
              {storeNames.map((n) => (
                <option key={n} value={n} />
              ))}
            </datalist>
            <datalist id="dl-payment">
              {PAYMENT_SUGGESTIONS.map((n) => (
                <option key={n} value={n} />
              ))}
            </datalist>
            {[
              [
                "Nome negozio",
                "store_name",
                "es. Mercato Rionale",
                "dl-store-names",
              ],
              ["Indirizzo negozio", "store_address", "opzionale", null],
              ["Data (GG/MM/AAAA)", "date", "", null],
              ["Ora (HH:MM)", "time", "", null],
              [
                "Metodo di pagamento",
                "payment_method",
                "contante / carta / …",
                "dl-payment",
              ],
            ].map(([label, field, placeholder, listId]) => (
              <div key={field}>
                <label className="block text-xs text-gray-400 mb-0.5">
                  {label}
                </label>
                <input
                  type="text"
                  value={form[field] || ""}
                  placeholder={placeholder}
                  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}
                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>

          <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>
            <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-24 text-right font-medium">€</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 items-center gap-2"
                >
                  <input
                    type="text"
                    value={item.name}
                    onChange={(e) =>
                      setItemField(item._key, "name", e.target.value)
                    }
                    className="flex-1 text-sm border border-gray-200 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-amber-300"
                    placeholder="Nome articolo"
                  />
                  <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-24 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.00"
                  />
                  <button
                    onClick={() => deleteItem(item._key)}
                    className="w-6 text-gray-300 hover:text-red-400 transition-colors text-base leading-none flex-shrink-0"
                    title="Rimuovi articolo"
                  >
                    ×
                  </button>
                </div>
              ))}
            </div>
            <button
              onClick={addItem}
              className="mt-3 text-xs text-amber-600 hover:text-amber-700 font-medium"
            >
              + Aggiungi articolo
            </button>
          </div>

          <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">
              Totale
            </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>
              <label className="block text-xs text-gray-400 mb-0.5">
                Totale pagato (€) — lascia vuoto per usare il totale articoli
              </label>
              <input
                type="text"
                inputMode="decimal"
                value={form.total_eur}
                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"
                placeholder={itemsSum.toFixed(2)}
              />
            </div>
            {totalMismatch && (
              <p className="text-xs text-amber-600 bg-amber-50 rounded-lg px-3 py-2">
                Il totale differisce dalla somma degli articoli (€
                {itemsSum.toFixed(2)}).
              </p>
            )}
          </div>

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