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

// 图片压缩 + 文档增强 (canvas, 无外部库)
FB.processImage = function (file, enhance) {
  return new Promise((resolve) => {
    if (!file.type.startsWith("image/")) { resolve(file); return; }
    const img = new Image();
    img.onload = function () {
      const MAX = 1600;
      let w = img.width, h = img.height;
      if (Math.max(w, h) > MAX) { const r = MAX / Math.max(w, h); w = Math.round(w * r); h = Math.round(h * r); }
      const c = document.createElement("canvas"); c.width = w; c.height = h;
      const ctx = c.getContext("2d");
      ctx.drawImage(img, 0, 0, w, h);
      if (enhance) {
        const d = ctx.getImageData(0, 0, w, h), p = d.data;
        // 轻度增强: 提对比 + 略提亮, 保留灰阶(不硬转黑白)
        const K = 1.35, B = 12;
        for (let i = 0; i < p.length; i += 4) {
          for (let k = 0; k < 3; k++) {
            let v = (p[i + k] - 128) * K + 128 + B;
            p[i + k] = v < 0 ? 0 : v > 255 ? 255 : v;
          }
        }
        ctx.putImageData(d, 0, 0);
      }
      c.toBlob((b) => {
        const f = new File([b], (file.name || "photo").replace(/\.\w+$/, "") + ".jpg", { type: "image/jpeg" });
        resolve(f);
      }, "image/jpeg", 0.82);
    };
    img.onerror = () => resolve(file);
    img.src = URL.createObjectURL(file);
  });
};

FB.ReceiveTab = function ReceiveTab({ lang, user }) {
  const { useState, useEffect } = React;
  const t = FB.makeT(lang);
  const [pos, setPos] = useState(null);
  const [sel, setSel] = useState(null);         // 选中的 PO
  const [kind, setKind] = useState("po");        // po | claim
  const [files, setFiles] = useState([]);        // {file, url, uploading, path}
  const [enhance, setEnhance] = useState(true);
  const [recv, setRecv] = useState({});
  const [claimInfo, setClaimInfo] = useState({ supplier: "", amount: "" });
  const [state, setState] = useState("idle");
  const [done, setDone] = useState(null);
  const [cancelling, setCancelling] = useState(null);   // 要取消的 PO (在别家买了的场景)
  const [cancelBusy, setCancelBusy] = useState(false);
  // 无单收货 (v20.1 方案A): 公司付但系统里没单的到货 — 之前只能错标成垫付
  const [noSupp, setNoSupp] = useState("");
  const [suppliers, setSuppliers] = useState(null);

  useEffect(() => { FB.api.pendingPOs().then(setPos); }, []);
  useEffect(() => { if (kind === "noorder" && !suppliers) FB.api.suppliersList().then(setSuppliers); }, [kind]);
  useEffect(() => {
    if (pos && FB.setPageInfo) FB.setPageInfo((lang === "zh" ? "待收 " : lang === "vi" ? "Chờ nhận " : "Pending ") + pos.length);
  }, [pos, lang]);

  async function doCancelPO() {
    if (!cancelling) return;
    setCancelBusy(true);
    const r = await FB.api.cancelPO({ po_id: cancelling.id, reason: lang === "zh" ? "在别家买了" : "bought elsewhere", by: user.name });
    setCancelBusy(false);
    if (r && r.ok) { setCancelling(null); FB.api.pendingPOs().then(setPos); }
  }

  // 草稿: 已上传的图 + 实收数 + claim 资料
  const dkey = "receive_" + kind + "_" + (sel ? sel.id : "new");
  useEffect(() => {
    const d = FB.draft.get(dkey, null);
    if (d) { setFiles(d.files || []); setRecv(d.recv || {}); if (d.claimInfo) setClaimInfo(d.claimInfo); }
  }, [dkey]);
  useEffect(() => {
    if (files.length || Object.keys(recv).length || claimInfo.supplier || claimInfo.amount)
      FB.draft.set(dkey, { files: files.filter((f) => f.path), recv, claimInfo });
  }, [files, recv, claimInfo, dkey]);

  const nm = (r) => {
    const i = r.items || {};
    return lang === "zh" ? (i.name_cn || r.item_code) : lang === "vi" ? (i.name_vn || i.name_en || r.item_code) : (i.name_en || i.name_cn || r.item_code);
  };
  const L = (zh, vi, en) => lang === "zh" ? zh : lang === "vi" ? vi : en;

  async function pick(ev) {
    const fs = Array.from(ev.target.files || []);
    for (const f of fs) {
      const idx = files.length;
      const processed = await FB.processImage(f, enhance);
      const local = URL.createObjectURL(processed);
      setFiles((x) => [...x, { name: processed.name, url: local, uploading: true }]);
      const prefix = (kind === "claim" ? "CLAIM" : kind === "noorder" ? "NOPO" : "INV") + "_" + (sel ? sel.supplier_name.replace(/\s+/g, "") : (noSupp || "misc").replace(/\s+/g, "")) + "_" + FB.todayLocal().replace(/-/g, "");
      const r = await FB.api.uploadInvoice(processed, prefix);
      setFiles((x) => x.map((it, i) => (it.url === local ? { ...it, uploading: false, path: r.path, err: r.error ? String(r.error.message || r.error) : null } : it)));
    }
    ev.target.value = "";
  }

  async function submit() {
    setState("sending");
    const payload = {
      po_id: kind === "po" && sel ? sel.id : null,
      files: files.filter((f) => f.path).map((f) => f.path),
      received: (sel ? sel.items : []).map((r) => ({ item_code: r.item_code, qty: recv[r.item_code] != null ? Number(recv[r.item_code]) : Number(r.qty_ordered) })),
      uploaded_by: user.name,
      paid_by: kind === "claim" ? "personal" : "company",
      // noorder: submit_receiving 会用 note.supplier 建一张「已到货」临时单, paid_by=company → 不会污染报销
      note: kind === "claim" ? { supplier: claimInfo.supplier, amount: claimInfo.amount }
          : kind === "noorder" ? { supplier: noSupp } : {},
    };
    const r = await FB.api.submitReceiving(payload);
    setState("idle");
    if (r && r.ok) {
      // 影子自动审核 (2026-07-29): 员工一交就 AI 读单 → 判定, 全程后台, 不挡完成画面。
      // 判定只写 meta 不入库; 老板审核页会看到「影子:会自动过 / 拦」。失败就算了,20:00 汇总兜底。
      if (r.po_id && payload.files.length) {
        FB.api.extractInvoice({ paths: payload.files, po_id: r.po_id })
          .then(() => FB.api.autoReview({ po_id: r.po_id }))
          .catch(() => {});
      }
      FB.draft.clear(dkey);
      setDone(true); setFiles([]); setRecv({}); setClaimInfo({ supplier: "", amount: "" }); setSel(null);
      FB.api.pendingPOs().then(setPos);
    } else setState("error");
  }

  if (done) return (
    <div className="px-4 py-16 max-w-md mx-auto text-center">
      <div className="text-5xl mb-3">✓</div>
      <p className="text-[17px] font-medium text-stone-800">{L("已送出，等老板审核", "Đã gửi, chờ duyệt", "Sent for review")}</p>
      <p className="text-[13px] text-stone-400 mt-2">{L("库存会在审核后更新", "Tồn kho cập nhật sau khi duyệt", "Stock updates after review")}</p>
      <button onClick={() => setDone(null)} className="mt-6 h-11 px-6 rounded-xl bg-red-700 text-white text-sm">
        {L("再传一张", "Gửi tiếp", "Upload another")}
      </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("收货登记", "Nhận hàng", "Receiving")}</h1>
      <p className="text-[12px] text-stone-400 px-1 mt-0.5 mb-3">
        {L("拍下单据 + 填实收数，老板审核后入库", "Chụp hóa đơn + số thực nhận", "Photo the invoice + actual qty")}
      </p>

      <div className="mb-3">
        <FB.UI.Seg options={[["po", L("供应商到货", "Hàng về", "Delivery")], ["claim", L("我垫付的", "Tôi ứng tiền", "I paid")]]}
          value={kind} onChange={(k) => { setKind(k); setSel(null); }} />
      </div>

      {kind === "po" && !sel && (
        <>
          <p className="text-[11px] text-stone-400 px-1 mb-1.5">{L("哪一张单到了?", "Đơn nào đã về?", "Which order arrived?")}</p>
          {!pos && <p className="text-sm text-stone-400 px-1">{t("loading")}</p>}
          {(pos || []).map((p) => {
            // 迟到几天: 过了 expected_date 还没收 → 越迟越红
            const late = p.expected_date ? Math.floor((Date.now() - new Date(p.expected_date).getTime()) / 86400000) : 0;
            const col = late > 3 ? "#A81E12" : late > 0 ? "#C2540A" : "#A07A06";
            return (
            <div key={p.id} className="relative mb-2">
              <button onClick={() => setSel(p)}
                className="w-full text-left rounded-xl border border-stone-200 bg-white p-3 active:bg-stone-50"
                style={{ borderLeft: "3px solid " + col }}>
                <div className="flex justify-between items-center">
                  <div className="min-w-0 flex-1">
                    <p className="text-[15px] font-medium text-stone-800">{p.supplier_name}</p>
                    <p className="text-[11px] text-stone-400 mt-0.5 flex items-center gap-1.5">
                      <span>{p.expected_date} · {p.items.length} {L("项", "món", "items")}</span>
                      {late > 0 ? <FB.UI.Chip tone={late > 3 ? "s1" : "s2"}>{L("迟 ", "trễ ", "late ") + late + L(" 天", " ngày", "d")}</FB.UI.Chip> : null}
                    </p>
                  </div>
                  <span className="text-stone-300 ml-2 mr-7"><FB.UI.Icon name="chev" size={15} /></span>
                </div>
              </button>
              {/* 取消: 下了单但最后在别家买 (如鸡蛋改在 Lotus/NSK) → 单永远卡在这里; 只 admin 可见 */}
              {user.role === "admin" ? (
                <button onClick={(e) => { e.stopPropagation(); setCancelling(p); }}
                  className="absolute top-1/2 -translate-y-1/2 right-1.5 w-8 h-8 rounded-lg flex items-center justify-center text-stone-300 active:bg-stone-100"
                  aria-label="cancel">
                  <FB.UI.Icon name="x" size={14} />
                </button>
              ) : null}
            </div>
            );
          })}
          {pos && pos.length === 0 && <p className="text-sm text-stone-400 px-1">{L("没有待收货的单", "Không có đơn chờ", "No pending orders")}</p>}

          {/* 无单收货入口 (方案A: 列表底部, 2026-07-29 Shanqian 选定) */}
          {pos && (
            <button onClick={() => setKind("noorder")}
              className="w-full flex items-center gap-2.5 rounded-xl p-3 mt-1 text-left active:bg-stone-50"
              style={{ border: "1.5px dashed #D6D3D1" }}>
              <span className="w-7 h-7 rounded-lg flex items-center justify-center shrink-0"
                style={{ background: "#FEF2F2", color: "#B91C1C" }}>
                <FB.UI.Icon name="plus" size={14} />
              </span>
              <span className="min-w-0">
                <span className="block text-[13px] font-medium text-stone-600">
                  {L("到货了，但上面没有这张单？", "Hàng đến nhưng không có đơn?", "Arrived but not listed?")}
                </span>
                <span className="block text-[10.5px] text-stone-400">
                  {L("选供应商拍单据 — 算公司付的", "Chọn nhà cung cấp + chụp hóa đơn", "Pick supplier + photo — company paid")}
                </span>
              </span>
            </button>
          )}
        </>
      )}

      {kind === "noorder" && (
        <>
          <button onClick={() => { setKind("po"); setNoSupp(""); }} className="text-[12px] text-stone-500 px-1 mb-2 flex items-center gap-1">
            <FB.UI.Icon name="back" size={13} />{L("回到货列表", "Quay lại", "Back to orders")}
          </button>
          <div className="rounded-xl border border-stone-200 bg-white p-3 mb-3">
            <p className="text-[11px] text-stone-400 mb-1.5">{L("哪家供应商送来的?", "Nhà cung cấp nào?", "Which supplier?")}</p>
            <select value={noSupp} onChange={(e) => setNoSupp(e.target.value)}
              className="w-full h-11 px-3 rounded-xl border border-stone-300 bg-white text-sm">
              <option value="">{L("— 选供应商 —", "— chọn —", "— pick —")}</option>
              {(suppliers || []).map((s) => <option key={s.name} value={s.name}>{s.name}</option>)}
            </select>
            <p className="text-[10.5px] text-stone-400 mt-2">
              {L("公司付的 · 品项由老板审核时对着单据填", "Công ty trả · món hàng do chủ điền khi duyệt", "Company paid · items filled at review")}
            </p>
          </div>
        </>
      )}

      {kind === "claim" && (
        <div className="rounded-xl border border-stone-200 bg-white p-3 mb-3">
          <input value={claimInfo.supplier} onChange={(e) => setClaimInfo({ ...claimInfo, supplier: e.target.value })}
            placeholder={L("在哪买的", "Mua ở đâu", "Bought from")}
            className="w-full h-11 px-3 rounded-xl border border-stone-300 text-sm mb-2" />
          <input value={claimInfo.amount} onChange={(e) => setClaimInfo({ ...claimInfo, amount: e.target.value })}
            type="number" inputMode="decimal" placeholder={L("金额 RM", "Số tiền RM", "Amount RM")}
            className="w-full h-11 px-3 rounded-xl border border-stone-300 text-sm" />
        </div>
      )}

      {sel && (
        <div className="rounded-xl border border-stone-200 bg-white p-3 mb-3">
          <div className="flex justify-between items-center mb-2">
            <p className="text-[15px] font-medium text-stone-800">{sel.supplier_name}</p>
            <button onClick={() => setSel(null)} className="text-[12px] text-stone-400">{L("换一张", "Đổi", "Change")}</button>
          </div>
          <p className="text-[11px] text-stone-400 mb-2">{L("实收数量（不同就改）", "SL thực nhận", "Actual received")}</p>
          {sel.items.map((r) => (
            <div key={r.item_code} className="flex items-center gap-2 py-1.5 border-t border-stone-50">
              <div className="flex-1 min-w-0">
                <p className="text-[14px] text-stone-800 truncate">{nm(r)}</p>
                <p className="text-[11px] text-stone-400">{L("订", "Đặt", "ordered")} {Number(r.qty_ordered)} {r.unit}</p>
              </div>
              <input type="number" inputMode="decimal"
                value={recv[r.item_code] != null ? recv[r.item_code] : Number(r.qty_ordered)}
                onChange={(e) => setRecv((x) => ({ ...x, [r.item_code]: e.target.value }))}
                className="w-16 h-9 px-2 rounded-lg border border-stone-300 text-center text-sm" />
              <span className="text-[10px] text-stone-400 w-8">{r.unit}</span>
            </div>
          ))}
        </div>
      )}

      {(sel || kind === "claim" || (kind === "noorder" && noSupp)) && (
        <>
          <div className="flex items-center gap-2 mb-2 px-1">
            <label className="flex items-center gap-1.5 text-[12px] text-stone-500">
              <input type="checkbox" checked={enhance} onChange={(e) => setEnhance(e.target.checked)} className="w-4 h-4 accent-red-700" />
              {L("文档增强（更清楚）", "Tăng nét", "Enhance")}
            </label>
          </div>
          <div className="flex gap-2 mb-3">
            <label className="flex-1 h-14 rounded-xl border border-stone-300 bg-white flex items-center justify-center gap-2 text-[14px] font-medium text-stone-700 active:bg-stone-50">
              <FB.UI.Icon name="camera" size={18} />{L("拍照", "Chụp", "Camera")}
              <input type="file" accept="image/*" capture="environment" onChange={pick} className="hidden" />
            </label>
            <label className="flex-1 h-14 rounded-xl border border-stone-300 bg-white flex items-center justify-center gap-2 text-[14px] font-medium text-stone-700 active:bg-stone-50">
              <FB.UI.Icon name="file" size={18} />{L("选档案", "Chọn tệp", "File")}
              <input type="file" accept="image/*,application/pdf" multiple onChange={pick} className="hidden" />
            </label>
          </div>

          {files.length > 0 && (
            <div className="grid grid-cols-3 gap-2 mb-3">
              {files.map((f, i) => (
                <div key={i} className="relative rounded-xl overflow-hidden border border-stone-200 bg-stone-50" style={{ aspectRatio: "3/4" }}>
                  <img src={f.url} alt="" className="w-full h-full object-cover" />
                  {f.uploading && (
                    <div className="absolute inset-0 bg-white/70 flex items-center justify-center">
                      <div style={{ width: 20, height: 20, borderRadius: "50%", border: "2.5px solid #E7E5E4", borderTopColor: "#B91C1C", animation: "fbspin .7s linear infinite" }} />
                    </div>
                  )}
                  {f.err && <div className="absolute inset-x-0 bottom-0 bg-red-700 text-white text-[9px] py-0.5 text-center">✕</div>}
                  {!f.uploading && !f.err && <div className="absolute top-1 right-1 text-white text-[11px] bg-green-600 rounded-full w-4 h-4 flex items-center justify-center">✓</div>}
                  <button onClick={() => setFiles((x) => x.filter((_, j) => j !== i))}
                    className="absolute bottom-1 right-1 bg-black/50 text-white text-[10px] rounded px-1.5">✕</button>
                </div>
              ))}
            </div>
          )}
          <p className="text-[11px] text-stone-400 px-1 mb-2">
            {L("单据两页?可以多拍几张", "Nhiều trang? Chụp thêm", "Multiple pages? Add more")}
            <br />💾 {L("已上传的会存着，刷新不丢", "Đã lưu, không mất khi tải lại", "auto-saved")}
          </p>
        </>
      )}

      {cancelling ? (
        <FB.UI.Sheet onClose={() => setCancelling(null)}>
          <p className="text-[16px] font-semibold text-stone-900 mb-1">{cancelling.supplier_name}</p>
          <p className="text-[13px] text-stone-500 mb-1">
            {L("这张单不会来了？(比如已经在别家买了)", "Đơn này không đến nữa?", "This order won't arrive?")}
          </p>
          <p className="text-[11px] text-stone-400 mb-4">
            {cancelling.items.map((r) => nm(r) + " ×" + Number(r.qty_ordered)).join(" · ")}
          </p>
          <div className="flex gap-2">
            <button onClick={() => setCancelling(null)}
              className="flex-1 h-12 rounded-xl border border-stone-200 text-stone-500 text-sm">
              {L("不是，留着", "Không, giữ lại", "No, keep it")}
            </button>
            <button onClick={doCancelPO} disabled={cancelBusy}
              className="flex-1 h-12 rounded-xl bg-red-700 text-white font-semibold disabled:opacity-40">
              {cancelBusy ? "…" : L("取消这单", "Hủy đơn này", "Cancel order")}
            </button>
          </div>
        </FB.UI.Sheet>
      ) : null}

      <style>{"@keyframes fbspin{to{transform:rotate(360deg)}}"}</style>

      <FB.UI.Sticky>
        <button onClick={submit}
          disabled={state === "sending" || !files.filter((f) => f.path).length || (kind === "po" && !sel) || (kind === "noorder" && !noSupp)}
          className="w-full h-12 rounded-xl bg-red-700 text-white font-semibold active:scale-[0.98] disabled:opacity-30">
          {state === "sending" ? t("submitting") : L("送出等审核", "Gửi duyệt", "Send for review")}
        </button>
      </FB.UI.Sticky>
    </div>
  );
};
