// Purchasing — merges the old Reorder + POs tabs. BUY: demand-driven suggestions grouped by
// vendor with one-tap "Create PO"; "make" items are flagged as builds. ORDERS: the PO list +
// status (receiving still happens on the floor via RECEIVING work orders). Manager/admin.
const { useState: useStatePU, useEffect: useEffectPU } = React;

function PurchasingTab({ user }) {
  const [sub, setSub] = useStatePU("BUY");
  const items = ["BUY", "ORDERS"];
  return (
    <div className="flex-1 flex flex-col overflow-hidden">
      <div className="px-4 sm:px-8 pt-5 pb-3 border-b border-zinc-800 flex gap-1">
        {items.map((i) => (
          <button key={i} onClick={() => setSub(i)}
            className={`h-10 px-5 rounded-lg font-display text-[15px] tracking-wider transition ${sub === i ? "bg-zinc-100 text-zinc-950" : "text-zinc-400 hover:bg-zinc-900 hover:text-zinc-200"}`}>
            {i === "BUY" ? "Buy / Reorder" : "Orders"}
          </button>
        ))}
      </div>
      {sub === "BUY" && <PurchasingBuy onCreated={() => setSub("ORDERS")} />}
      {sub === "ORDERS" && (window.POsTab ? <window.POsTab user={user} /> : <div className="p-8 text-zinc-500">Orders view unavailable.</div>)}
    </div>
  );
}

function PurchasingBuy({ onCreated }) {
  const [rows, setRows] = useStatePU(null);      // null = loading; par-based reorder candidates
  const [gen, setGen] = useStatePU(false);

  function load() {
    fetch("/api/purchasing/candidates").then((r) => r.json()).then((d) => setRows(Array.isArray(d) ? d : [])).catch(() => setRows([]));
  }
  useEffectPU(() => { load(); }, []);

  // Draft (or top up) one PO per vendor from every below-par part, then jump to Orders to review.
  async function generateDrafts() {
    setGen(true);
    try {
      const res = await fetch("/api/purchasing/reorder-drafts", { method: "POST", headers: { "Content-Type": "application/json" } });
      const d = await res.json();
      if (res.ok) {
        const added = (d.drafts || []).reduce((n, x) => n + (x.lines_added || 0), 0);
        window.gpsToast && window.gpsToast({
          message: d.candidates === 0 ? "Everything's at or above par — no drafts needed" : `${d.drafts.length} vendor draft(s) · ${added} line(s) added`,
          tone: "ok",
        });
        if (window.gpsRefreshData) window.gpsRefreshData();
        if (d.candidates > 0) { onCreated && onCreated(); return; }
        load();
      } else { window.gpsToast && window.gpsToast({ message: d.error || "Couldn't generate drafts", tone: "warn" }); }
    } catch (_) { window.gpsToast && window.gpsToast({ message: "Couldn't reach the server", tone: "warn" }); }
    setGen(false);
  }

  const byVendor = {};
  (rows || []).forEach((r) => { const v = r.vendor || "(no vendor)"; (byVendor[v] = byVendor[v] || []).push(r); });
  const vendors = Object.keys(byVendor).sort();
  const totalItems = (rows || []).length;

  const Row = (r) => (
    <div key={r.sku} className="grid grid-cols-[1.9fr_0.8fr_0.8fr_0.8fr_0.7fr] gap-2 px-4 py-2.5 items-center text-[13px]">
      <div className="min-w-0"><div className="text-zinc-100 truncate">{r.name || r.sku}</div><div className="font-mono text-[11px] text-zinc-500 truncate">{r.sku}</div></div>
      <div className="font-mono text-zinc-400 tabular-nums">{r.on_hand}/{r.par} <span className="text-zinc-600">on hand/par</span></div>
      <div className="font-mono text-zinc-400 tabular-nums">{r.weekly_demand}/wk</div>
      <div className="font-mono text-zinc-400 tabular-nums">{r.lead_days}d lead</div>
      <div className="text-right font-display text-[20px] text-zinc-100" title="Order up to par (incl. lead-time demand), min MOQ, rounded to case-pack">{r.qty}</div>
    </div>
  );

  return (
    <div className="flex-1 px-4 sm:px-8 py-5 overflow-y-auto">
      <div className="max-w-[1100px] mx-auto space-y-6">
        <div className="flex items-end justify-between gap-3 flex-wrap">
          <div>
            <h1 className="font-display text-[30px] sm:text-[40px] tracking-tight leading-none">Below par</h1>
            <p className="text-[13px] text-zinc-500 mt-1">Parts under their par level, with an order-up-to-par quantity (accounts for MOQ, case-pack, and lead-time demand). Items already on an open PO are hidden.</p>
          </div>
          {totalItems > 0 && (
            <button onClick={generateDrafts} disabled={gen}
              className="h-11 px-5 rounded-lg text-white text-[14px] font-display tracking-wider disabled:opacity-50 whitespace-nowrap" style={{ background: window.GPS_RED }}>
              {gen ? "GENERATING…" : "⚡ GENERATE DRAFT POs"}
            </button>
          )}
        </div>

        {rows === null ? (
          <div className="text-zinc-600 text-[14px] py-10 text-center">Loading…</div>
        ) : totalItems === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 text-center gap-3">
            <div className="text-[40px]">✅</div>
            <div className="font-display text-[22px] text-zinc-300">Everything's at par</div>
            <div className="text-[13px] text-zinc-500 max-w-md">No buy-parts are below par (or they're already on an open PO). Set par levels on parts in Inventory or the BOM editor to drive auto-reorder.</div>
          </div>
        ) : (
          <>
            {vendors.map((v) => {
              const grp = byVendor[v];
              const est = grp.reduce((s, r) => s + (r.qty || 0) * (r.unit_cost || 0), 0);
              return (
                <div key={v} className="bg-zinc-900 border border-zinc-800 rounded-2xl overflow-hidden">
                  <div className="flex items-center justify-between gap-3 px-4 py-3 border-b border-zinc-800">
                    <div className="min-w-0"><div className="text-[14px] text-zinc-100 font-medium truncate">{v}</div><div className="text-[11px] text-zinc-500">{grp.length} item{grp.length !== 1 ? "s" : ""} · ~${est.toFixed(0)}</div></div>
                  </div>
                  <div className="grid grid-cols-[1.9fr_0.8fr_0.8fr_0.8fr_0.7fr] gap-2 px-4 py-2 text-[10px] uppercase tracking-wider text-zinc-600 border-b border-zinc-800/60">
                    <div>Part</div><div>Stock</div><div>Demand</div><div>Lead</div><div className="text-right">Order</div>
                  </div>
                  <div className="divide-y divide-zinc-800/80">{grp.map(Row)}</div>
                </div>
              );
            })}
          </>
        )}
      </div>
    </div>
  );
}

window.PurchasingTab = PurchasingTab;
