// Worker inventory tab — table view with audit-style flow.
// Two modes:
//   - free (default): worker can spot-update any SKU, no "submit"
//   - audit (started from a weekly AUDIT WO): tracks progress, final submit, completion summary
//
// Layout is the same as AuditSession: search + filter + table + per-row qty/bin inputs.
// On-the-way column shows admin-ordered restock + ETA, so worker can see incoming stock.

const { useState: useStateWI, useEffect: useEffectWI, useMemo: useMemoWI } = React;

function WorkerInventoryTab({ user, auditWo, onCompleteAudit, onExitAudit }) {
  const auditMode = !!auditWo;
  const inv = window.INVENTORY || [];

  const [items, setItems] = useStateWI(() =>
    inv.map((it) => ({
      sku: it.sku, name: it.name, type: it.type,
      systemQty: it.qty, qty: it.qty,
      systemLoc: it.location || "—", location: it.location || "",
      onOrder: it.onOrder || 0, eta: it.eta || null,
      reserved: it.reserved || 0,
      par: it.par,
      status: it.status,
      checked: false,   // audit mode only
      dirty: false,
    }))
  );
  const [filter, setFilter] = useStateWI(auditMode ? "REMAINING" : "ALL");
  const [search, setSearch] = useStateWI("");
  const [pauseModal, setPauseModal] = useStateWI(false);
  const [elapsed, setElapsed] = useStateWI(0);

  useEffectWI(() => {
    if (!auditMode) return;
    const t = setInterval(() => setElapsed((e) => e + 1), 1000);
    return () => clearInterval(t);
  }, [auditMode]);

  function elapsedFmt() {
    const m = Math.floor(elapsed / 60); const s = elapsed % 60;
    return `00:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
  }

  const counts = useMemoWI(() => {
    const done = items.filter((i) => i.checked).length;
    const remaining = items.length - done;
    const diffs = items.filter((i) => i.qty !== i.systemQty || (i.location && i.location !== i.systemLoc)).length;
    return { total: items.length, done, remaining, diffs };
  }, [items]);

  const filtered = useMemoWI(() => {
    const q = search.trim().toLowerCase();
    return items.filter((it) => {
      if (auditMode && filter === "REMAINING" && it.checked) return false;
      if (filter === "DIFF" && it.qty === it.systemQty && it.location === it.systemLoc) return false;
      if (filter === "INCOMING" && !it.onOrder) return false;
      if (filter === "LOW" && it.status === "OK") return false;
      if (q && !`${it.sku} ${it.name}`.toLowerCase().includes(q)) return false;
      return true;
    });
  }, [items, filter, search, auditMode]);

  function updateItem(sku, patch) {
    setItems((arr) => arr.map((it) => it.sku === sku ? { ...it, ...patch, dirty: true } : it));
    // Apply qty/location changes immediately to underlying window.INVENTORY (audit mode commits at end)
    if (!auditMode && (patch.qty != null || patch.location != null)) {
      const ref = (window.INVENTORY || []).find((x) => x.sku === sku);
      if (ref) {
        if (patch.qty != null) ref.qty = patch.qty;
        if (patch.location != null) ref.location = patch.location;
      }
    }
  }

  function commitAudit() {
    // commit all dirty rows back to window.INVENTORY
    items.forEach((it) => {
      if (!it.dirty) return;
      const ref = (window.INVENTORY || []).find((x) => x.sku === it.sku);
      if (ref) { ref.qty = it.qty; if (it.location) ref.location = it.location; }
    });
    onCompleteAudit && onCompleteAudit({ counts, items });
  }

  return (
    <div className={`flex-1 flex flex-col ${auditMode ? "" : ""}`}>
      {/* Audit-mode top bar */}
      {auditMode && (
        <header className="border-b border-zinc-800 bg-zinc-900/40 px-6 h-[64px] flex items-center justify-between flex-shrink-0">
          <div className="flex items-center gap-3">
            <button onClick={() => setPauseModal(true)}
              className="h-10 px-3 rounded-lg bg-amber-500/15 border border-amber-500/40 text-amber-200 text-[13px] font-medium hover:bg-amber-500/25 uppercase tracking-wider flex items-center gap-2">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>
              Pause
            </button>
            <button onClick={onExitAudit}
              className="h-10 px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-200 text-[13px] font-medium hover:bg-zinc-700 uppercase tracking-wider">
              ← Queue
            </button>
            <span className="font-mono text-[13px] text-zinc-500">{auditWo.id}</span>
            <span className="px-2 py-1 rounded text-[11px] font-bold uppercase tracking-wider bg-zinc-700/30 text-zinc-200 border border-zinc-600/50">WEEKLY AUDIT</span>
          </div>
          <div className="flex items-center gap-5 text-[14px]">
            <div className="text-zinc-400">Elapsed <span className="font-mono text-zinc-200">{elapsedFmt()}</span></div>
            <div className="text-zinc-300">{user.name}</div>
          </div>
        </header>
      )}

      {/* Title + counters */}
      <div className="px-6 pt-5 pb-3 border-b border-zinc-800/50 flex-shrink-0 space-y-3">
        <div className="flex items-end justify-between flex-wrap gap-3">
          <div>
            <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">
              {auditMode ? "Weekly inventory walk" : "Inventory"}
            </div>
            <div className="font-display text-[36px] tracking-tight leading-tight mt-1">
              {auditMode ? auditWo.name : "Update counts and locations"}
            </div>
            {!auditMode && (
              <div className="text-[13px] text-zinc-500 mt-1 max-w-[640px]">
                See a discrepancy on the shelf? Update qty or bin location inline. Changes save instantly and log to the activity feed.
              </div>
            )}
          </div>
          <div className="flex items-center gap-2">
            {auditMode ? (
              <>
                <Counter label="Done" value={counts.done} tone="ok" />
                <Counter label="Remaining" value={counts.remaining} />
                <Counter label="Adjusted" value={counts.diffs} tone={counts.diffs > 0 ? "warn" : "neutral"} />
                <Counter label="Total" value={counts.total} />
              </>
            ) : (
              <>
                <Counter label="SKUs" value={counts.total} />
                <Counter label="Incoming" value={items.filter((i) => i.onOrder > 0).length} tone="ok" />
              </>
            )}
          </div>
        </div>
        {auditMode && (
          <div className="h-2.5 rounded-full bg-zinc-800 overflow-hidden">
            <div className="h-full bg-emerald-500 transition-all" style={{ width: `${(counts.done / counts.total) * 100}%` }} />
          </div>
        )}
      </div>

      {/* Filters */}
      <div className="px-6 py-3 border-b border-zinc-800/50 flex items-center gap-3 flex-shrink-0 flex-wrap">
        <input value={search} onChange={(e) => setSearch(e.target.value)}
          placeholder="Search SKU or part…"
          className="h-11 px-3 bg-zinc-900 border border-zinc-800 rounded-lg text-zinc-100 text-[14px] outline-none focus:border-zinc-600 w-[280px]" />
        <div className="flex gap-1 bg-zinc-900 border border-zinc-800 rounded-lg p-1">
          {(auditMode
            ? [["REMAINING", "Remaining"], ["DIFF", "Adjusted"], ["ALL", "All"]]
            : [["ALL", "All"], ["INCOMING", "Incoming"], ["DIFF", "Adjusted"]]
          ).map(([k, label]) => (
            <button key={k} onClick={() => setFilter(k)}
              className={`h-9 px-3 rounded-md text-[12px] font-display tracking-wider transition ${
                filter === k ? "bg-zinc-100 text-zinc-950" : "text-zinc-400 hover:text-zinc-200"
              }`}>
              {label}
            </button>
          ))}
        </div>
        <div className="ml-auto text-[12px] text-zinc-500">
          {auditMode
            ? "Walk every bay and verify each SKU. Confirm or edit each row."
            : "All changes log automatically · admin sees on-the-way column matches sent POs."}
        </div>
      </div>

      {/* Table */}
      <div className={`${auditMode ? "flex-1" : "flex-1"} overflow-y-auto px-6 py-4`}>
        <div className="max-w-[1400px] mx-auto bg-zinc-900 border border-zinc-800 rounded-xl overflow-hidden">
          <div className="grid grid-cols-[1.5fr_2fr_1.2fr_1.2fr_1.3fr_0.9fr] text-[11px] uppercase tracking-wider text-zinc-500 px-4 py-3 border-b border-zinc-800 bg-zinc-950/50">
            <div>SKU</div>
            <div>Part</div>
            <div>Qty on hand</div>
            <div>Bin / shelf</div>
            <div>On the way · ETA</div>
            <div className="text-right">{auditMode ? "Status" : "Save"}</div>
          </div>
          {filtered.length === 0 ? (
            <div className="px-4 py-12 text-center text-zinc-500 text-[14px]">
              {auditMode && filter === "REMAINING" ? "✓ Everything checked." : "No matches."}
            </div>
          ) : (
            <div className="divide-y divide-zinc-800/80">
              {filtered.map((it) => (
                <Row key={it.sku} it={it} auditMode={auditMode} onChange={(p) => updateItem(it.sku, p)} />
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Audit-mode footer */}
      {auditMode && (
        <div className="px-6 py-4 border-t border-zinc-800 bg-zinc-950 flex items-center gap-4 flex-shrink-0">
          <div className="flex-1 text-[13px] text-zinc-400">
            {counts.remaining > 0 ? (
              <>{counts.remaining} SKU{counts.remaining !== 1 ? "s" : ""} remaining. {counts.diffs} update{counts.diffs !== 1 ? "s" : ""} to commit.</>
            ) : (
              <span className="text-emerald-400">All SKUs checked. Submit to commit {counts.diffs} update{counts.diffs !== 1 ? "s" : ""}.</span>
            )}
          </div>
          <window.HoldButton color="emerald" holdMs={500} onComplete={commitAudit}
            disabled={counts.done === 0}
            className="h-[64px] px-6 min-w-[320px]"
            subText="submit audit · commits all updates">
            <div className="font-display text-[22px] tracking-wider">
              ✓ FINISH AUDIT ({counts.done}/{counts.total})
            </div>
          </window.HoldButton>
        </div>
      )}

      {pauseModal && (
        <window.PauseModal
          context={`Audit · ${counts.done}/${counts.total} checked · ${counts.diffs} adjustment${counts.diffs !== 1 ? "s" : ""} logged`}
          onCancel={() => setPauseModal(false)}
          onPause={() => { setPauseModal(false); onExitAudit && onExitAudit(); }}
          onMaterialResolved={() => setPauseModal(false)}
        />
      )}
    </div>
  );
}

function Row({ it, auditMode, onChange }) {
  const qtyDiff = it.qty !== it.systemQty;
  const locDiff = it.location && it.location !== it.systemLoc;
  const hasIncoming = it.onOrder > 0;
  const pending = it.eta === "pending approval";

  function quickConfirm() {
    onChange({ checked: true });
  }
  function saveNow() {
    window.gpsToast && window.gpsToast({
      message: `${it.sku} updated${qtyDiff ? ` · qty ${it.qty}` : ""}${locDiff ? ` · bin ${it.location}` : ""}`,
      tone: "ok",
    });
    onChange({ dirty: false, systemQty: it.qty, systemLoc: it.location || it.systemLoc });
  }

  return (
    <div className={`grid grid-cols-[1.5fr_2fr_1.2fr_1.2fr_1.3fr_0.9fr] items-center gap-3 px-4 py-3 ${auditMode && it.checked ? "bg-emerald-500/[0.04]" : ""}`}>
      <div>
        <div className="font-mono text-[10px] text-zinc-500 uppercase tracking-wider">{it.type}</div>
        <div className="font-mono text-[13px] text-zinc-200">{it.sku}</div>
      </div>
      <div className="text-[14px] min-w-0">
        <div className="truncate">{it.name}</div>
        {it.reserved > 0 && (
          <div className="text-[11px] text-zinc-500 mt-0.5">{it.reserved} reserved</div>
        )}
      </div>

      {/* Qty */}
      <div className="flex items-center gap-1.5">
        <button onClick={() => onChange({ qty: Math.max(0, it.qty - 1) })}
          className="h-[40px] w-[34px] rounded bg-zinc-800 border border-zinc-700 text-[16px] font-display flex-shrink-0">−</button>
        <input type="number" value={it.qty}
          onChange={(e) => onChange({ qty: Math.max(0, parseInt(e.target.value || "0", 10)) })}
          className={`h-[48px] flex-1 min-w-0 bg-zinc-950 border-2 rounded text-center font-display text-[18px] tabular-nums outline-none focus:border-zinc-500 ${
            qtyDiff ? "border-amber-500/50" : "border-zinc-800"
          }`} />
        <button onClick={() => onChange({ qty: it.qty + 1 })}
          className="h-[40px] w-[34px] rounded bg-zinc-800 border border-zinc-700 text-[16px] font-display flex-shrink-0">+</button>
      </div>

      {/* Location */}
      <div>
        <input value={it.location} onChange={(e) => onChange({ location: e.target.value.toUpperCase() })}
          placeholder={it.systemLoc}
          className={`h-[48px] w-full bg-zinc-950 border-2 rounded text-center font-mono text-[14px] tabular-nums outline-none focus:border-zinc-500 ${
            locDiff ? "border-amber-500/50" : "border-zinc-800"
          }`} />
        {locDiff && <div className="text-[10px] text-amber-400 mt-0.5">was {it.systemLoc}</div>}
      </div>

      {/* On the way */}
      <div>
        {hasIncoming ? (
          <div className={`rounded-lg px-3 py-2 border ${pending ? "bg-amber-500/10 border-amber-500/30" : "bg-sky-500/10 border-sky-500/30"}`}>
            <div className="flex items-baseline gap-1">
              <span className="font-display text-[20px] tabular-nums leading-none">{it.onOrder}</span>
              <span className="text-[11px] text-zinc-400 uppercase tracking-wider">on the way</span>
            </div>
            <div className={`text-[11px] mt-1 ${pending ? "text-amber-300" : "text-sky-300"}`}>
              {pending ? "⏳ pending admin approval" : `arrives ${it.eta}`}
              <span className="text-zinc-500 ml-1 font-mono">{it.onOrderPo}</span>
            </div>
          </div>
        ) : (
          <div className="text-[12px] text-zinc-600">—</div>
        )}
      </div>

      {/* Status / Save */}
      <div className="flex items-center justify-end gap-1.5">
        {auditMode ? (
          it.checked ? (
            qtyDiff || locDiff ? (
              <span className="px-2 py-1 rounded text-[10px] font-bold uppercase tracking-wider bg-amber-500/15 text-amber-300 border border-amber-500/40">
                ⚠ ADJUSTED
              </span>
            ) : (
              <span className="px-2 py-1 rounded text-[10px] font-bold uppercase tracking-wider bg-emerald-500/15 text-emerald-300 border border-emerald-500/40">
                ✓ OK
              </span>
            )
          ) : (
            <button onClick={quickConfirm}
              className="h-9 px-3 rounded bg-emerald-500 text-zinc-950 text-[11px] font-display tracking-wider hover:bg-emerald-400">
              CONFIRM
            </button>
          )
        ) : (
          it.dirty ? (
            <button onClick={saveNow}
              className="h-9 px-3 rounded bg-emerald-500 text-zinc-950 text-[11px] font-display tracking-wider hover:bg-emerald-400">
              SAVE
            </button>
          ) : (
            <span className="text-[11px] text-zinc-600 uppercase tracking-wider">live</span>
          )
        )}
      </div>
    </div>
  );
}

function Counter({ label, value, tone = "neutral" }) {
  const color =
    tone === "ok" ? "text-emerald-400" :
    tone === "warn" ? "text-amber-400" :
    "text-zinc-100";
  return (
    <div className="bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 min-w-[80px] text-right">
      <div className="text-[10px] uppercase tracking-wider text-zinc-500">{label}</div>
      <div className={`font-display text-[22px] tabular-nums leading-none mt-0.5 ${color}`}>{value}</div>
    </div>
  );
}

window.WorkerInventoryTab = WorkerInventoryTab;
