// Screen 11: POs Tab
const { useState: useStatePO, useMemo: useMemoPO } = React;

const PO_STATUS = {
  SENT: { color: "bg-sky-500/15 text-sky-200 border-sky-500/40" },
  RECEIVED: { color: "bg-emerald-500/15 text-emerald-200 border-emerald-500/40" },
  PARTIAL: { color: "bg-amber-500/15 text-amber-200 border-amber-500/40" },
};

function POsTab({ user }) {
  const [selected, setSelected] = useStatePO(null);
  const [showNew, setShowNew] = useStatePO(false);
  const [extraPOs, setExtraPOs] = useStatePO([]);
  const [pendingReqs, setPendingReqs] = useStatePO(window.PENDING_PO_REQUESTS || []);

  const allPOs = useMemoPO(() => [...extraPOs, ...window.PURCHASE_ORDERS], [extraPOs]);

  if (selected) return <PODetail po={selected} onBack={() => setSelected(null)} />;

  function handleCreate(po) {
    setExtraPOs((p) => [po, ...p]);
    setShowNew(false);
    window.gpsToast && window.gpsToast({
      message: `${po.id} queued · included in admin digest at ${window.NOTIFICATION_CONFIG?.adminDigestNextSend || "next send"}`,
      tone: "ok",
      undo: () => setExtraPOs((p) => p.filter((x) => x.id !== po.id)),
    });
  }

  function sendDigestNow() {
    const count = pendingReqs.length + extraPOs.length;
    window.gpsToast && window.gpsToast({
      message: `Digest sent to ${window.NOTIFICATION_CONFIG?.adminDigestRecipient} · ${count} requests bundled`,
      tone: "ok",
    });
    setPendingReqs([]);
  }
  function dismissReq(id) {
    setPendingReqs((p) => p.filter((r) => r.id !== id));
    window.gpsToast && window.gpsToast({
      message: `Request ${id} removed from digest`,
      tone: "info",
    });
  }
  function approveReq(req) {
    const po = {
      id: `GPS-PO-2026-0${143 + Math.floor(Math.random() * 50)}`,
      vendor: req.vendor, items: 1, total: req.estCost,
      status: "SENT", sent: "today", expected: "+" + (window.VENDORS.find(v => v.name === req.vendor)?.leadTime || 7) + "d",
      lines: [{ sku: req.sku, vendorSku: "—", desc: req.name, ordered: req.suggestedQty, received: 0, unit: req.estCost / req.suggestedQty }],
    };
    setExtraPOs((p) => [po, ...p]);
    dismissReq(req.id);
  }

  return (
    <div className="flex-1 px-8 py-6 overflow-y-auto">
      <div className="max-w-[1200px] mx-auto space-y-4">
        <div className="flex items-center justify-between">
          <div className="font-display text-[36px] tracking-tight">Purchase Orders</div>
          <button onClick={() => setShowNew(true)}
            className="h-12 px-5 rounded-lg font-display text-[16px] tracking-wider text-zinc-100 hover:opacity-90"
            style={{ background: window.GPS_RED }}>
            + NEW PO
          </button>
        </div>

        {/* Daily digest banner */}
        <div className="bg-zinc-900 border border-zinc-800 border-l-[6px] border-l-amber-400 rounded-xl p-5 flex items-center gap-5 flex-wrap">
          <div className="h-12 w-12 rounded-lg bg-amber-500/15 border border-amber-500/30 flex items-center justify-center text-amber-300 text-[22px]">
            📧
          </div>
          <div className="flex-1 min-w-[300px]">
            <div className="text-[11px] uppercase tracking-[0.22em] text-amber-300 font-semibold">Daily admin digest</div>
            <div className="font-display text-[24px] tracking-tight leading-tight mt-0.5">
              {pendingReqs.length + extraPOs.length} requests batched for{" "}
              <span className="text-amber-200">{window.NOTIFICATION_CONFIG?.adminDigestNextSend || "next send"}</span>
            </div>
            <div className="text-[13px] text-zinc-400 mt-1">
              PO requests don't email immediately. They're bundled into one digest sent to{" "}
              <span className="font-mono text-zinc-300">{window.NOTIFICATION_CONFIG?.adminDigestRecipient || "admin"}</span>{" "}
              once per day at <span className="text-zinc-300 font-mono">{window.NOTIFICATION_CONFIG?.adminDigestTime || "08:00"}</span>. Configurable in Settings → Integrations.
            </div>
            <div className="text-[12px] text-zinc-500 mt-1">Last sent: {window.NOTIFICATION_CONFIG?.adminDigestLastSent}</div>
          </div>
          <button onClick={sendDigestNow}
            disabled={(pendingReqs.length + extraPOs.length) === 0}
            className="h-12 px-5 rounded-lg bg-amber-400 text-zinc-950 font-display text-[14px] tracking-wider hover:bg-amber-300 disabled:opacity-40 disabled:cursor-not-allowed">
            SEND DIGEST NOW
          </button>
        </div>

        {/* Pending requests queue */}
        {pendingReqs.length > 0 && (
          <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>
                <div className="font-display text-[22px] tracking-wider text-zinc-300">PENDING REQUESTS · {pendingReqs.length}</div>
                <div className="text-[12px] text-zinc-500 mt-0.5">Approve to convert into a sent PO, or wait for the digest.</div>
              </div>
            </div>
            <div className="divide-y divide-zinc-800/80">
              {pendingReqs.map((r) => (
                <div key={r.id} className="grid grid-cols-[110px_1.4fr_1.4fr_0.9fr_0.9fr_220px] items-center gap-3 px-5 py-3 text-[14px]">
                  <div>
                    <div className="font-mono text-[12px] text-zinc-500">{r.id}</div>
                    {r.priority === "URGENT" && (
                      <span className="mt-1 inline-block px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-red-500 text-white">● URGENT</span>
                    )}
                  </div>
                  <div className="min-w-0">
                    <div className="font-mono text-[12px] text-zinc-400 truncate">{r.sku}</div>
                    <div className="truncate">{r.name}</div>
                  </div>
                  <div className="text-[13px]">
                    <div className="text-zinc-400">{r.vendor}</div>
                    <div className="text-zinc-500 text-[12px]">{r.source} · {r.requestedBy}</div>
                  </div>
                  <div className="text-right">
                    <div className="font-display text-[20px] tabular-nums leading-none">{r.suggestedQty}</div>
                    <div className="text-[11px] text-zinc-500">suggested qty</div>
                  </div>
                  <div className="text-right">
                    <div className="font-display text-[20px] tabular-nums leading-none">${r.estCost.toFixed(0)}</div>
                    <div className="text-[11px] text-zinc-500">est total</div>
                  </div>
                  <div className="flex gap-2 justify-end">
                    <button onClick={() => dismissReq(r.id)}
                      className="h-9 px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-300 text-[12px] uppercase tracking-wider hover:bg-zinc-700">
                      Dismiss
                    </button>
                    <button onClick={() => approveReq(r)}
                      className="h-9 px-4 rounded-lg bg-emerald-500 text-zinc-950 text-[12px] font-display tracking-wider hover:bg-emerald-400">
                      APPROVE · SEND NOW
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl overflow-hidden">
          <div className="grid grid-cols-[2fr_2fr_0.8fr_1fr_1fr_1fr_1fr] text-[11px] uppercase tracking-wider text-zinc-500 px-5 py-3 border-b border-zinc-800 bg-zinc-950/60">
            <div>PO #</div><div>Vendor</div><div className="text-right">Items</div><div className="text-right">Total</div><div>Status</div><div>Sent</div><div>Expected</div>
          </div>
          <div className="divide-y divide-zinc-800">
            {allPOs.map((po) => (
              <button key={po.id} onClick={() => setSelected(po)}
                className="w-full grid grid-cols-[2fr_2fr_0.8fr_1fr_1fr_1fr_1fr] items-center px-5 py-4 text-[14px] text-left hover:bg-zinc-800/50">
                <div className="font-mono text-zinc-200">{po.id}</div>
                <div>{po.vendor}</div>
                <div className="text-right tabular-nums">{po.items}</div>
                <div className="text-right tabular-nums">${po.total.toFixed(2)}</div>
                <div>
                  <span className={`px-2 py-1 rounded text-[11px] font-bold tracking-wider uppercase border ${PO_STATUS[po.status].color}`}>
                    {po.status}
                  </span>
                </div>
                <div className="text-zinc-400">{po.sent}</div>
                <div className="text-zinc-400">{po.expected}</div>
              </button>
            ))}
          </div>
        </div>

        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-5">
          <div className="font-display text-[22px] tracking-wider text-zinc-300 mb-3">VENDORS</div>
          <div className="grid grid-cols-[2fr_2fr_1fr_1fr_1fr] text-[11px] uppercase tracking-wider text-zinc-500 px-2 pb-2 border-b border-zinc-800">
            <div>Name</div><div>Email</div><div className="text-right">Lead</div><div className="text-right">Products</div><div className="text-right">Reliability</div>
          </div>
          <div className="divide-y divide-zinc-800/60">
            {window.VENDORS.map((v) => (
              <div key={v.name} className="grid grid-cols-[2fr_2fr_1fr_1fr_1fr] items-center px-2 py-2 text-[14px]">
                <div>{v.name}</div>
                <div className="font-mono text-[12px] text-zinc-400">{v.email}</div>
                <div className="text-right tabular-nums">{v.leadTime}d</div>
                <div className="text-right tabular-nums">{v.products}</div>
                <div className="text-right tabular-nums">
                  <span className={v.reliability >= 95 ? "text-emerald-400" : v.reliability >= 90 ? "text-amber-400" : "text-red-400"}>{v.reliability}%</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
      {showNew && <NewPOModal onClose={() => setShowNew(false)} onCreate={handleCreate} />}
    </div>
  );
}

function NewPOModal({ onClose, onCreate }) {
  const [vendor, setVendor] = useStatePO(window.VENDORS[0].name);
  // candidates: items that are below par
  const candidates = window.INVENTORY.filter((it) => it.qty < it.par && it.type !== "kit" && it.type !== "assy");
  const [lines, setLines] = useStatePO(
    candidates.slice(0, 2).map((it) => ({
      sku: it.sku, name: it.name,
      qty: Math.max(it.par * 2 - it.qty, 50),
      unit: 1.5,
    }))
  );
  const [pickerOpen, setPickerOpen] = useStatePO(false);

  const total = lines.reduce((s, l) => s + l.qty * l.unit, 0);

  function addLine(it) {
    if (lines.some((l) => l.sku === it.sku)) return;
    setLines([...lines, { sku: it.sku, name: it.name, qty: Math.max(it.par - it.qty, 25), unit: 1.5 }]);
    setPickerOpen(false);
  }
  function updateLine(i, patch) {
    setLines(lines.map((l, idx) => (idx === i ? { ...l, ...patch } : l)));
  }
  function removeLine(i) { setLines(lines.filter((_, idx) => idx !== i)); }

  function submit() {
    const id = `GPS-PO-2026-0${143 + Math.floor(Math.random() * 50)}`;
    onCreate({
      id, vendor, items: lines.length, total,
      status: "SENT", sent: "May 20", expected: "May 27",
      lines: lines.map((l) => ({
        sku: l.sku, vendorSku: "—", desc: l.name,
        ordered: l.qty, received: 0, unit: l.unit,
      })),
    });
  }

  return (
    <div className="fixed inset-0 z-50 bg-zinc-950/85 backdrop-blur-sm flex items-center justify-center p-8">
      <div className="w-full max-w-[920px] bg-zinc-900 border border-zinc-800 rounded-2xl flex flex-col max-h-[90vh]">
        <div className="px-8 pt-7 pb-5 border-b border-zinc-800">
          <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">New purchase order</div>
          <div className="font-display text-[40px] tracking-tight mt-1">Draft a PO</div>
        </div>

        <div className="flex-1 overflow-y-auto px-8 py-5 space-y-5">
          <div>
            <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">Vendor</div>
            <select value={vendor} onChange={(e) => setVendor(e.target.value)}
              className="w-full h-[56px] px-4 bg-zinc-950 border border-zinc-800 rounded-xl text-[17px] outline-none focus:border-zinc-600">
              {window.VENDORS.map((v) => <option key={v.name} value={v.name}>{v.name} · lead {v.leadTime}d · {v.reliability}% reliable</option>)}
            </select>
          </div>

          <div>
            <div className="flex items-center justify-between mb-2">
              <div className="text-[12px] uppercase tracking-wider text-zinc-400">Line items · {lines.length}</div>
              <button onClick={() => setPickerOpen((o) => !o)}
                className="h-9 px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-200 text-[12px] font-display tracking-wider hover:bg-zinc-700">
                + ADD LINE
              </button>
            </div>

            {pickerOpen && (
              <div className="bg-zinc-950 border border-zinc-800 rounded-lg mb-2 max-h-[200px] overflow-y-auto divide-y divide-zinc-800/60">
                {window.INVENTORY.filter((it) => it.type !== "kit" && it.type !== "assy" && !lines.some((l) => l.sku === it.sku)).map((it) => (
                  <button key={it.sku} onClick={() => addLine(it)}
                    className="w-full grid grid-cols-[1.4fr_2fr_0.6fr_0.6fr] items-center px-3 py-2 text-[13px] text-left hover:bg-zinc-800/60">
                    <div className="font-mono text-zinc-300">{it.sku}</div>
                    <div className="truncate">{it.name}</div>
                    <div className="text-right tabular-nums text-zinc-400">{it.qty}/{it.par}</div>
                    <div className="text-right text-emerald-400 text-[11px] uppercase tracking-wider">add +</div>
                  </button>
                ))}
              </div>
            )}

            <div className="bg-zinc-950 border border-zinc-800 rounded-xl divide-y divide-zinc-800/80">
              {lines.map((l, i) => (
                <div key={l.sku} className="grid grid-cols-[1.4fr_2fr_1fr_1fr_40px] items-center gap-2 px-3 py-2.5 text-[13px]">
                  <div className="font-mono text-zinc-200">{l.sku}</div>
                  <div className="truncate">{l.name}</div>
                  <input type="number" value={l.qty} onChange={(e) => updateLine(i, { qty: parseInt(e.target.value || "0", 10) })}
                    className="h-10 px-3 bg-zinc-900 border border-zinc-800 rounded-md text-right tabular-nums outline-none focus:border-zinc-600" />
                  <div className="flex items-center gap-1">
                    <span className="text-zinc-500">$</span>
                    <input type="number" step="0.01" value={l.unit} onChange={(e) => updateLine(i, { unit: parseFloat(e.target.value || "0") })}
                      className="h-10 px-2 bg-zinc-900 border border-zinc-800 rounded-md text-right tabular-nums outline-none focus:border-zinc-600 w-full" />
                  </div>
                  <button onClick={() => removeLine(i)}
                    className="h-8 w-8 rounded text-zinc-400 hover:bg-red-500/20 hover:text-red-300 flex items-center justify-center">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                  </button>
                </div>
              ))}
              {lines.length === 0 && (
                <div className="px-3 py-6 text-center text-zinc-500 text-[14px]">No lines yet. Tap ADD LINE.</div>
              )}
            </div>
          </div>

          <div className="bg-zinc-950 border border-zinc-800 rounded-xl px-5 py-4 flex items-center justify-between">
            <div className="text-[12px] uppercase tracking-wider text-zinc-500">Total</div>
            <div className="font-display text-[36px] tabular-nums">${total.toFixed(2)}</div>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3 px-8 py-5 border-t border-zinc-800">
          <button onClick={onClose}
            className="h-[64px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[18px] tracking-wider hover:bg-zinc-700">
            CANCEL
          </button>
          <button onClick={submit} disabled={lines.length === 0}
            className="h-[64px] rounded-xl bg-emerald-500 text-zinc-950 font-display text-[18px] tracking-wider hover:bg-emerald-400 disabled:opacity-40 disabled:cursor-not-allowed">
            SEND PO TO {vendor.split(" ")[0].toUpperCase()}
          </button>
        </div>
      </div>
    </div>
  );
}

function PODetail({ po, onBack }) {
  return (
    <div className="flex-1 px-8 py-6 overflow-y-auto">
      <div className="max-w-[1100px] mx-auto space-y-5">
        <button onClick={onBack}
          className="h-10 px-4 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-200 text-[14px] hover:bg-zinc-700 uppercase tracking-wider">
          ← All POs
        </button>

        <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-6">
          <div className="flex items-start justify-between">
            <div>
              <div className="font-mono text-[14px] text-zinc-400">{po.id}</div>
              <div className="font-display text-[36px] tracking-tight mt-1">{po.vendor}</div>
              <div className="text-[14px] text-zinc-400 mt-1">
                Sent {po.sent} · Expected {po.expected} · {po.lines.length} line items
              </div>
            </div>
            <div className="flex items-center gap-2">
              <span className={`px-3 py-1.5 rounded-md text-[12px] font-bold tracking-wider uppercase border ${PO_STATUS[po.status].color}`}>
                {po.status}
              </span>
              <button className="h-10 px-4 rounded-lg bg-emerald-500 text-zinc-950 font-display text-[14px] tracking-wider hover:bg-emerald-400"
                onClick={() => window.gpsToast && window.gpsToast({ message: `PDF for ${po.id} sent to your email`, tone: "ok" })}>
                SEND PDF TO MY EMAIL
              </button>
            </div>
          </div>

          <div className="mt-5 bg-zinc-950 border border-zinc-800 rounded-xl overflow-hidden">
            <div className="grid grid-cols-[1.4fr_1.2fr_2fr_0.8fr_0.8fr_0.8fr_0.8fr] text-[11px] uppercase tracking-wider text-zinc-500 px-4 py-3 border-b border-zinc-800 bg-zinc-950/60">
              <div>GPS SKU</div><div>Vendor SKU</div><div>Description</div><div className="text-right">Ordered</div><div className="text-right">Received</div><div className="text-right">Unit</div><div className="text-right">Line</div>
            </div>
            <div className="divide-y divide-zinc-800/60">
              {po.lines.map((line) => {
                const lineTotal = line.unit * line.ordered;
                const recvPct = (line.received / line.ordered) * 100;
                return (
                  <div key={line.sku} className="grid grid-cols-[1.4fr_1.2fr_2fr_0.8fr_0.8fr_0.8fr_0.8fr] items-center px-4 py-3 text-[13px] gap-2">
                    <div className="font-mono text-zinc-200">{line.sku}</div>
                    <div className="font-mono text-zinc-400">{line.vendorSku}</div>
                    <div>{line.desc}</div>
                    <div className="text-right tabular-nums">{line.ordered}</div>
                    <div className="text-right">
                      <div className="tabular-nums">{line.received}</div>
                      {line.received > 0 && line.received < line.ordered && (
                        <div className="h-1 mt-1 rounded-full bg-zinc-800 overflow-hidden">
                          <div className="h-full bg-amber-400" style={{ width: `${recvPct}%` }} />
                        </div>
                      )}
                    </div>
                    <div className="text-right tabular-nums text-zinc-400">${line.unit.toFixed(2)}</div>
                    <div className="text-right tabular-nums">${lineTotal.toFixed(2)}</div>
                  </div>
                );
              })}
            </div>
            <div className="grid grid-cols-[1.4fr_1.2fr_2fr_0.8fr_0.8fr_0.8fr_0.8fr] items-center px-4 py-3 border-t border-zinc-800 bg-zinc-950 text-[14px] gap-2">
              <div className="col-span-6 text-right text-zinc-400 uppercase tracking-wider text-[11px]">Total</div>
              <div className="text-right font-display text-[20px] tabular-nums">${po.total.toFixed(2)}</div>
            </div>
          </div>

          <div className="mt-4 flex gap-3">
            <button className="h-12 px-4 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-100 text-[13px] font-display tracking-wider hover:bg-zinc-700"
              onClick={() => window.gpsToast && window.gpsToast({ message: `Downloading PDF for ${po.id}…`, tone: "info" })}>
              RE-DOWNLOAD PDF
            </button>
            <button className="h-12 px-4 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-100 text-[13px] font-display tracking-wider hover:bg-zinc-700"
              onClick={() => window.gpsToast && window.gpsToast({ message: `Line marked received · inventory updated`, tone: "ok", undo: () => {} })}>
              MARK LINE RECEIVED
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.POsTab = POsTab;
