// Returns receiving portal (GPS-FEAT-2). A worker identifies a return by Shopify order /
// customer, records each line's condition, and dispositions it: intact → restock to sellable
// stock, damaged → quarantine. All stock moves run through the server's single write service.
const { useState: useStateRT, useEffect: useEffectRT } = React;

function ReturnsTab({ user }) {
  const [orderRef, setOrderRef] = useStateRT("");
  const [customer, setCustomer] = useStateRT("");
  const [reason, setReason] = useStateRT("");
  const [lines, setLines] = useStateRT([]);
  const [recent, setRecent] = useStateRT([]);
  const [busy, setBusy] = useStateRT(false);
  const [lookupBusy, setLookupBusy] = useStateRT(false);

  function refresh() {
    fetch("/api/returns?limit=50").then((r) => r.json()).then((d) => setRecent(Array.isArray(d) ? d : [])).catch(() => {});
  }
  useEffectRT(() => { refresh(); }, []);

  async function lookup() {
    if (!orderRef.trim()) return;
    setLookupBusy(true);
    try {
      const d = await fetch(`/api/returns/order/${encodeURIComponent(orderRef.trim())}`).then((r) => r.json());
      const found = (d.lines || []).map((l) => ({ sku: l.sku, name: l.name || l.sku, qty: l.qty || 1, condition: "intact", disposition: "restock" }));
      if (found.length) setLines(found);
      else window.gpsToast && window.gpsToast({ message: `No shipped lines found for ${orderRef.trim()} — add lines manually`, tone: "info" });
    } catch (_) { window.gpsToast && window.gpsToast({ message: "Lookup failed", tone: "warn" }); }
    setLookupBusy(false);
  }

  const setLine = (i, patch) => setLines((ls) => ls.map((l, idx) => (idx === i ? { ...l, ...patch } : l)));
  const removeLine = (i) => setLines((ls) => ls.filter((_, idx) => idx !== i));
  const addLine = () => setLines((ls) => [...ls, { sku: "", name: "", qty: 1, condition: "intact", disposition: "restock" }]);
  // Condition drives the default disposition; the packer can still override the disposition.
  const setCondition = (i, condition) => setLine(i, { condition, disposition: condition === "damaged" ? "quarantine" : "restock" });

  async function submit() {
    const payload = lines
      .filter((l) => l.sku && Number(l.qty) > 0)
      .map((l) => ({ sku: l.sku.trim(), qty: Number(l.qty), condition: l.condition, disposition: l.disposition }));
    if (!payload.length) { window.gpsToast && window.gpsToast({ message: "Add at least one line with a SKU + qty", tone: "warn" }); return; }
    setBusy(true);
    try {
      const r = await fetch("/api/returns", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Idempotency-Key": window.gpsIdemKey() },
        body: JSON.stringify({ order_ref: orderRef.trim(), customer: customer.trim(), reason: reason.trim(), lines: payload }),
      });
      const d = await r.json().catch(() => ({}));
      if (r.ok) {
        window.gpsToast && window.gpsToast({ message: `Return received · ${(d.processed || payload).length} line(s)`, tone: "ok" });
        setOrderRef(""); setCustomer(""); setReason(""); setLines([]); refresh();
      } else window.gpsToast && window.gpsToast({ message: d.error || "Could not record return", tone: "warn" });
    } catch (_) { window.gpsToast && window.gpsToast({ message: "Server unreachable — not recorded", tone: "warn" }); }
    setBusy(false);
  }

  const I = "h-11 bg-zinc-950 border border-zinc-700 rounded-lg px-3 text-[14px] outline-none focus:border-zinc-500";

  return (
    <div className="flex-1 px-4 sm:px-8 py-5 sm:py-6 overflow-y-auto">
      <div className="max-w-[1000px] mx-auto space-y-6">
        <div>
          <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Returns</div>
          <h1 className="font-display text-[32px] sm:text-[44px] tracking-tight leading-none mt-1">Receive a return</h1>
          <p className="text-[13px] text-zinc-500 mt-1">Identify the order, log each item's condition, and disposition it. Intact restocks to sellable stock; damaged routes to quarantine.</p>
        </div>

        {/* Identify */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-5 space-y-3">
          <div className="text-[11px] uppercase tracking-wider text-zinc-500">Who / what</div>
          <div className="grid grid-cols-1 sm:grid-cols-[1fr_1fr_auto] gap-3">
            <input className={I} placeholder="Shopify order # (e.g. #1234)" value={orderRef} onChange={(e) => setOrderRef(e.target.value)} />
            <input className={I} placeholder="Customer (optional)" value={customer} onChange={(e) => setCustomer(e.target.value)} />
            <button onClick={lookup} disabled={lookupBusy || !orderRef.trim()}
              className="h-11 px-5 rounded-lg bg-zinc-800 border border-zinc-700 text-[13px] font-display tracking-wider hover:bg-zinc-700 disabled:opacity-50 whitespace-nowrap">
              {lookupBusy ? "Looking…" : "Look up order →"}
            </button>
          </div>
          <input className={`${I} w-full`} placeholder="Reason (optional)" value={reason} onChange={(e) => setReason(e.target.value)} />
        </div>

        {/* Lines */}
        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl overflow-hidden">
          <div className="px-5 py-4 border-b border-zinc-800 flex items-center justify-between">
            <div className="font-display text-[20px] tracking-wider text-zinc-300">RETURNED ITEMS</div>
            <button onClick={addLine} className="h-9 px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-[12px] font-display tracking-wider hover:bg-zinc-700">+ ADD LINE</button>
          </div>
          {lines.length === 0 ? (
            <div className="px-5 py-10 text-center text-zinc-600 text-[14px]">Look up an order or add lines manually.</div>
          ) : (
            <div className="divide-y divide-zinc-800/80">
              {lines.map((l, i) => (
                <div key={i} className="grid grid-cols-1 sm:grid-cols-[1.4fr_0.6fr_1fr_1fr_auto] items-center gap-3 px-5 py-3">
                  <div>
                    <input className={`${I} w-full font-mono text-[13px]`} placeholder="SKU" value={l.sku} onChange={(e) => setLine(i, { sku: e.target.value })} />
                    {l.name && l.name !== l.sku && <div className="text-[12px] text-zinc-500 mt-1 truncate">{l.name}</div>}
                  </div>
                  <input type="number" min="1" className={`${I} w-full text-center`} value={l.qty} onChange={(e) => setLine(i, { qty: Math.max(1, parseInt(e.target.value) || 1) })} />
                  <div className="flex gap-1">
                    {["intact", "damaged"].map((c) => (
                      <button key={c} onClick={() => setCondition(i, c)}
                        className={`flex-1 h-11 rounded-lg text-[12px] font-bold uppercase tracking-wider border ${l.condition === c ? (c === "damaged" ? "bg-red-500/15 text-red-300 border-red-500/40" : "bg-emerald-500/15 text-emerald-300 border-emerald-500/40") : "bg-zinc-800 text-zinc-500 border-zinc-700 hover:text-zinc-300"}`}>
                        {c}
                      </button>
                    ))}
                  </div>
                  <select className={`${I} w-full`} value={l.disposition} onChange={(e) => setLine(i, { disposition: e.target.value })}>
                    <option value="restock">restock → sellable</option>
                    <option value="quarantine">quarantine</option>
                    <option value="scrap">scrap</option>
                  </select>
                  <button onClick={() => removeLine(i)} className="h-9 w-9 rounded text-zinc-500 hover:bg-red-500/20 hover:text-red-300 flex items-center justify-center justify-self-end">✕</button>
                </div>
              ))}
            </div>
          )}
        </div>

        <button onClick={submit} disabled={busy || lines.length === 0}
          className="w-full h-14 rounded-xl bg-emerald-600 text-zinc-950 font-display text-[20px] tracking-wider hover:bg-emerald-500 disabled:opacity-50">
          {busy ? "RECORDING…" : "RECEIVE RETURN →"}
        </button>

        {/* Recent */}
        <div>
          <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500 mb-3">Recent returns</div>
          {recent.length === 0 ? (
            <div className="text-[13px] text-zinc-600">No returns logged yet.</div>
          ) : (
            <div className="bg-zinc-900 border border-zinc-800 rounded-2xl overflow-hidden divide-y divide-zinc-800/80">
              {recent.map((r) => (
                <div key={r.id} className="flex items-center justify-between gap-3 px-5 py-3 text-[13px]">
                  <div className="min-w-0">
                    <span className="font-mono text-zinc-200">{r.sku}</span>
                    <span className="text-zinc-500 ml-2">×{r.qty}</span>
                    {r.order_ref && <span className="text-zinc-500 ml-2">· {r.order_ref}</span>}
                    {r.customer && <span className="text-zinc-600 ml-2 hidden sm:inline">· {r.customer}</span>}
                  </div>
                  <div className="flex items-center gap-2 flex-shrink-0">
                    <span className={`px-2 py-0.5 rounded text-[11px] font-bold uppercase tracking-wider border ${r.condition === "damaged" ? "bg-red-500/10 text-red-300 border-red-500/30" : "bg-emerald-500/10 text-emerald-300 border-emerald-500/30"}`}>{r.condition || "—"}</span>
                    <span className="text-zinc-500 text-[12px]">{r.disposition}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.ReturnsTab = ReturnsTab;
