window.FB = window.FB || {};

// 订货页 (admin) — 2026-07-29 Shanqian 选定 V2: 总列表 + 一键按供应商拆单
// 数据: FB.api.reorder() (减库存 + 绿灯不催单 + 扣不了在途 — 在途由 reorder 的 v_safety_line 链路外扣? 不 —
//       在途扣减在 create 之后自然发生: PO 已下单 → 下次 reorder 前应扣。见下 loadData 注释)
// 建单 = create_po Edge Function, 只写「已下单」不动库存; 库存等收货审核。
FB.OrderTab = function OrderTab({ lang, user }) {
  const { useState, useEffect } = React;
  const t = FB.makeT(lang);
  const L = (zh, vi, en) => (lang === "zh" ? zh : lang === "vi" ? vi : en);

  const [sug, setSug] = useState(null);        // reorder() 结果
  const [intransit, setIntransit] = useState(null); // {item_code: qty} 已下单未到货
  const [rows, setRows] = useState({});        // {code: {on, qty}}
  const [paid, setPaid] = useState({});        // {supplier: true=垫付}
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState(null);      // {created:[], text}
  const [err, setErr] = useState(null);
  const [copied, setCopied] = useState(false);

  // reorder() 没扣在途 (它只看 安全线−理论库存) → 这里自己扣,
  // 不然刚建完单刷新一次,同样的量又全冒出来。
  function loadData() {
    setSug(null); setErr(null);
    Promise.all([FB.api.reorder(), FB.api.openPoQty()]).then(([r, it]) => {
      setIntransit(it);
      const cleaned = (r || []).map((x) => {
        const cs = Number(x.carton_size) || 0;
        const inQ = Number(it[x.code]) || 0;          // 在途量(品项单位)
        const gapLeft = Number(x.gap) - inQ;          // 扣在途后的净缺口
        if (gapLeft <= 0) return null;
        // 2026-07-30 Shanqian:「订货 kg 整数就行」— 一律进整
        let qty = cs > 0 ? Math.ceil(gapLeft / cs) : Math.ceil(gapLeft);
        const moq = Number(x.moq) || 0;
        if (moq > 0) { const mq = cs > 0 ? Math.ceil(moq / cs) : moq; if (qty < mq) qty = mq; }
        return { ...x, qty0: qty };
      }).filter(Boolean);
      setSug(cleaned);
      const init = {};
      cleaned.forEach((x) => (init[x.code] = { on: true, qty: x.qty0 }));
      setRows(init);
    });
  }
  useEffect(() => { loadData(); }, []);
  useEffect(() => {
    if (sug && FB.setPageInfo) {
      const n = Object.values(rows).filter((r) => r.on && Number(r.qty) > 0).length;
      FB.setPageInfo(L("待订 ", "Cần đặt ", "To order ") + n);
    }
  }, [sug, rows, lang]);

  const unitOf = (x) => (Number(x.carton_size) > 0 ? "ctn" : (x.unit || ""));

  // 按供应商分组 (reorder 已按 supplier 排序)
  const groups = [];
  (sug || []).forEach((x) => {
    const s = x.supplier_name || L("未知供应商", "Không rõ", "Unknown");
    let g = groups.find((y) => y.s === s);
    if (!g) { g = { s, lt: (Number(x.lt) || 0), buf: (Number(x.buffer) || 0), items: [] }; groups.push(g); }
    g.items.push(x);
  });
  const picked = (g) => g.items.filter((x) => rows[x.code] && rows[x.code].on && Number(rows[x.code].qty) > 0);
  const activeGroups = groups.filter((g) => picked(g).length > 0);
  const totalItems = activeGroups.reduce((a, g) => a + picked(g).length, 0);

  // WhatsApp 行: 「数量 单位 供应商叫法」; China 附换算 (同驾驶舱 orderLine 规则)
  function waLine(x, supplier) {
    const q = Number(rows[x.code].qty);
    const cs = Number(x.carton_size) || 0;
    const name = x.alias || x.name_cn || x.code;
    if (!cs) return q + " " + (x.unit || "") + " " + name;
    const conv = (FB.PCS_SUPPLIERS || []).some((s) => FB.sameSupplier(supplier, s));
    return conv ? q + " ctn (" + +(q * cs).toFixed(2) + " " + (x.unit || "") + ") " + name
                : q + " ctn " + name;
  }
  function waText(gs) {
    return gs.map((g) => g.s + "\n" + picked(g).map((x) => waLine(x, g.s)).join("\n")).join("\n\n");
  }

  async function createAll() {
    if (!activeGroups.length) return;
    setBusy(true); setErr(null);
    const today = FB.todayLocal();
    const orders = activeGroups.map((g) => {
      const d = new Date(); d.setDate(d.getDate() + (g.lt || 0));
      return {
        supplier_name: g.s,
        order_date: today,
        expected_date: g.lt > 0 ? FB.localDate(d) : null,
        paid_by: paid[g.s] ? "personal" : "company",
        note: "订货页建单",
        lines: picked(g).map((x) => {
          const cs = Number(x.carton_size) || 0;
          const q = Number(rows[x.code].qty);
          // PO 存品项单位 (收货实收按品项单位填): 有箱规 → 箱数×箱规
          return { item_code: x.code, qty: cs > 0 ? Math.round(q * cs * 1000) / 1000 : q, unit: x.unit || null };
        }),
      };
    });
    const r = await FB.api.createPo({ orders, ordered_by: user.name });
    setBusy(false);
    if (!r || r.error || !r.ok) { setErr(String((r && r.error) || "failed").slice(0, 160)); return; }
    const text = waText(activeGroups);
    setDone({ created: r.created, text });
    if (navigator.clipboard && navigator.clipboard.writeText)
      navigator.clipboard.writeText(text).then(() => setCopied(true), () => {});
  }

  // ── 建完 ──
  if (done) return (
    <div className="px-3 py-3 max-w-md mx-auto pb-24">
      <div className="text-center py-6">
        <div className="mx-auto mb-3 flex items-center justify-center" style={{ width: 52, height: 52 }}>
          <FB.UI.CheckCircle on size={52} />
        </div>
        <p className="text-[17px] font-semibold text-stone-900">
          {L("建好 " + done.created.length + " 张单", "Đã tạo " + done.created.length + " đơn", done.created.length + " POs created")}
        </p>
        <p className="text-[12px] text-stone-400 mt-1">
          {L("员工收货页已经看得到 · 不动库存,收货审核才入", "Nhân viên đã thấy ở trang nhận hàng", "Visible in Receiving now")}
        </p>
      </div>
      <div className="rounded-xl border border-stone-200 bg-white divide-y divide-stone-100 overflow-hidden mb-3">
        {done.created.map((c) => (
          <div key={c.po_id} className="flex justify-between px-3 py-2 text-sm">
            <span className="text-stone-800">{c.supplier_name}</span>
            <span className="text-stone-400">#{c.po_id} · {c.items} {L("项", "món", "items")}</span>
          </div>
        ))}
      </div>
      <div className="rounded-xl p-3 mb-2" style={{ background: "#1C1917" }}>
        <p className="text-[10px] text-stone-400 mb-1.5">WhatsApp</p>
        <pre className="text-[12px] text-white whitespace-pre-wrap leading-relaxed" style={{ fontFamily: "inherit" }}>{done.text}</pre>
      </div>
      <button onClick={() => { navigator.clipboard && navigator.clipboard.writeText(done.text); setCopied(true); }}
        className="w-full h-11 rounded-xl border border-stone-300 text-stone-600 text-sm mb-2 flex items-center justify-center gap-1.5">
        <FB.UI.Icon name="copy" size={14} />{copied ? "✓ " + L("已复制", "Đã chép", "Copied") : L("复制", "Chép", "Copy")}
      </button>
      <button onClick={() => { setDone(null); setCopied(false); loadData(); }}
        className="w-full h-11 rounded-xl bg-red-700 text-white text-sm font-semibold">
        {L("回订货页", "Quay lại", "Back to ordering")}
      </button>
    </div>
  );

  return (
    <div className="px-3 py-3 max-w-md mx-auto pb-28">
      <h1 className="text-[20px] font-semibold text-stone-900 px-1">{L("订货", "Đặt hàng", "Ordering")}</h1>
      <p className="text-[12px] text-stone-400 px-1 mt-0.5 mb-3">
        {L("缺口 = 安全线 − 库存 − 在途 · 绿灯不催 · 勾好一键建单", "Thiếu = mức an toàn − tồn − đang về", "gap = safety − stock − in transit")}
      </p>

      {!sug && <p className="text-sm text-stone-400 px-1">{t("loading")}</p>}
      {sug && sug.length === 0 && (
        <div className="rounded-xl border border-stone-200 bg-white p-6 text-center text-sm text-stone-500">
          ✓ {L("按算法今天没有要订的", "Hôm nay không cần đặt gì", "Nothing to order today")}
        </div>
      )}

      {groups.map((g) => {
        // 供应商级开关 (2026-07-30 Shanqian 提): 点供应商名整组勾/取消, 不用一项一项戳
        const anyOn = g.items.some((x) => rows[x.code] && rows[x.code].on);
        const toggleSup = () => {
          const on = !anyOn;
          setRows((rs) => {
            const next = { ...rs };
            g.items.forEach((x) => { next[x.code] = { ...(next[x.code] || { qty: x.qty0 }), on }; });
            return next;
          });
        };
        return (
        <div key={g.s} className="mb-3" style={anyOn ? {} : { opacity: 0.45 }}>
          <div className="flex items-center gap-2 px-1 mb-1">
            {/* 字号跟品项行一致 (13.5px), 勾框也同尺寸 — 2026-07-30 Shanqian 提 */}
            <button onClick={toggleSup} className="flex items-center gap-2 min-w-0">
              <FB.UI.CheckCircle on={anyOn} size={26} square />
              <span className={"text-[13.5px] font-semibold truncate " + (anyOn ? "text-stone-700" : "text-stone-400 line-through")}>{g.s}</span>
            </button>
            <span className="text-[10.5px] text-stone-400 shrink-0">LT {g.lt + g.buf}{L("天", " ngày", "d")}</span>
            <label className="ml-auto flex items-center gap-1 text-[11px] text-stone-500 shrink-0">
              <input type="checkbox" checked={!!paid[g.s]}
                onChange={(e) => setPaid((p) => ({ ...p, [g.s]: e.target.checked }))}
                className="w-3.5 h-3.5 accent-red-700" />
              {L("我垫付", "Tôi ứng", "I paid")}
            </label>
          </div>
          <div className="rounded-xl border border-stone-200 bg-white divide-y divide-stone-50 overflow-hidden"
            style={{ borderLeft: "3px solid " + (g.lt + g.buf >= 30 ? "#A81E12" : g.lt + g.buf >= 8 ? "#C2540A" : "#A07A06") }}>
            {g.items.map((x) => {
              const r = rows[x.code] || {};
              return (
                <div key={x.code} className="flex items-center gap-2.5 px-3 py-2">
                  <button onClick={() => setRows((rs) => ({ ...rs, [x.code]: { ...rs[x.code], on: !(rs[x.code] || {}).on } }))}>
                    <FB.UI.CheckCircle on={!!r.on} size={26} square />
                  </button>
                  <div className="flex-1 min-w-0">
                    <p className={"text-[13.5px] truncate " + (r.on ? "text-stone-900" : "text-stone-400 line-through")}>{FB.nm(x, lang)}</p>
                    <p className="text-[10.5px] text-stone-400">
                      {L("存", "tồn", "have")} {Math.round(Number(x.on_hand) * 10) / 10} · {L("线", "mức", "line")} {Math.round(Number(x.safety_line) * 10) / 10}
                    </p>
                  </div>
                  <input type="number" inputMode="decimal" value={r.qty === 0 ? "0" : (r.qty || "")}
                    onChange={(e) => { const v = parseFloat(e.target.value); setRows((rs) => ({ ...rs, [x.code]: { ...rs[x.code], qty: isNaN(v) ? 0 : Math.max(0, v) } })); }}
                    className="w-14 h-9 px-1 rounded-lg border border-stone-200 text-center text-[15px] font-semibold tabular-nums" />
                  <span className="text-[10px] text-stone-400 w-7">{unitOf(x)}</span>
                </div>
              );
            })}
          </div>
        </div>
        );
      })}

      {err && <div className="rounded-xl p-3 mb-2 text-[12px]" style={{ background: "#FCEDEA", color: "#A81E12" }}>{err}</div>}

      {sug && sug.length > 0 && (
        <FB.UI.Sticky>
          <button onClick={createAll} disabled={busy || !totalItems}
            className="w-full h-12 rounded-xl bg-red-700 text-white font-semibold active:scale-[0.98] disabled:opacity-30">
            {busy ? t("submitting")
              : L("建 " + activeGroups.length + " 张单 · " + totalItems + " 项",
                  "Tạo " + activeGroups.length + " đơn · " + totalItems + " món",
                  "Create " + activeGroups.length + " POs · " + totalItems + " items")}
          </button>
          <p className="text-[10.5px] text-stone-400 text-center mt-1.5">
            {L("按供应商自动拆单 · WhatsApp 文本一起复制", "Tách đơn theo nhà cung cấp", "Splits per supplier · copies WhatsApp text")}
          </p>
        </FB.UI.Sticky>
      )}
    </div>
  );
};
