/* global React, Icon, Button, ModeToggle, useToast, ImportBanner, runImportProgress, PageHead, SkuToolbar */
// 商品調整 Oracle 匯出 L2 — 單批次明細（Johnny only，唯讀）
// 前綴 AOD_ 避免與 OracleDetail (OD_) 等全域名稱衝突

const { useState } = React;

// ── Column definitions（同新商品 Oracle 匯出精選 19 欄 / 全欄位） ────────────
const AOD_col = (key, label, w, group, opts = {}) => ({ key, label, w, group, ...opts });

const AOD_GROUP_LABELS = {
  A: "基本識別", B: "供應", C: "分類", D: "商務",
  E: "法規/合規", F: "配送", G: "規格", H: "商品資訊", I: "進貨資訊",
};

const AOD_COMPACT_COLS = [
  AOD_col("#",           "#",              48,  "A", { sticky: true }),
  AOD_col("barcode",     "品號",           140, "A", { mono: true, sticky2nd: true }),
  AOD_col("name",        "品名",           240, "A"),
  AOD_col("supplierName","廠商名稱",        160, "B"),
  AOD_col("mainCat",     "主類別",          110, "C"),
  AOD_col("subCat",      "次類別",          110, "C"),
  AOD_col("brand",       "品牌",            110, "C"),
  AOD_col("listPrice",   "牌價",            100, "D", { num: true, nt: true }),
  AOD_col("cost",        "進價（未稅）",    100, "D", { num: true, nt: true }),
  AOD_col("taxRate",     "稅率",             80, "D"),
  AOD_col("minOrder",    "最低訂購量",        90, "D", { num: true }),
  AOD_col("deliv",       "配貨方式",          90, "F"),
  AOD_col("temp",        "溫層",             80, "F"),
  AOD_col("specSummary", "規格摘要",         160, "G"),
  AOD_col("estSales",    "預估業績/月",      120, "I", { num: true, nt: true }),
  AOD_col("origCost",    "原進價",           100, "I", { num: true, nt: true }),
  AOD_col("promoCost",   "促進進價",         100, "I", { num: true, nt: true }),
  AOD_col("promoStart",  "促進開始",         110, "I", { mono: true }),
  AOD_col("promoEnd",    "促進結束",         110, "I", { mono: true }),
];

const AOD_FULL_COLS = [
  AOD_col("#",                "#",                     48,  "A", { sticky: true }),
  AOD_col("barcode",          "品號",                  140, "A", { mono: true, sticky2nd: true }),
  AOD_col("name",             "品名",                  240, "A"),
  AOD_col("twCode",           "TW Code",               200, "A", { mono: true }),
  AOD_col("supplierName",     "廠商名稱",               160, "B"),
  AOD_col("supplierNo",       "廠商編號",               130, "B", { mono: true }),
  AOD_col("secSupplierName",  "次要廠商名稱",            160, "B"),
  AOD_col("secSupplierPartNo","次要廠商品號",            160, "B", { mono: true }),
  AOD_col("mainCat",          "主類別",                 110, "C"),
  AOD_col("subCat",           "次類別",                 110, "C"),
  AOD_col("segment1",         "大分類(分析用)",          140, "C"),
  AOD_col("segment2",         "次分類(分析用)",          140, "C"),
  AOD_col("segment3",         "子分類(分析用)",          140, "C"),
  AOD_col("brand",            "品牌",                   110, "C"),
  AOD_col("listPrice",        "牌價",                   100, "D", { num: true, nt: true }),
  AOD_col("cost",             "進價（未稅）",            100, "D", { num: true, nt: true }),
  AOD_col("taxRate",          "稅率",                    80, "D"),
  AOD_col("minOrder",         "最低訂購量",               90, "D", { num: true }),
  AOD_col("shelfDays",        "保存期限（天）",           110, "E", { num: true }),
  AOD_col("expType",          "效期類型",                130, "E"),
  AOD_col("dangerousGoods",   "危險品",                  100, "E"),
  AOD_col("supplierEccn",     "ECCN 分類",               110, "E", { mono: true }),
  AOD_col("unNumber",         "UN 危品編號",              110, "E", { mono: true }),
  AOD_col("msdsUrl",          "MSDS 連結",               180, "E"),
  AOD_col("htsCode",          "HTS 關稅代碼",            130, "E", { mono: true }),
  AOD_col("origin",           "產地",                    90, "E"),
  AOD_col("imported",         "進口/台灣",                90, "E"),
  AOD_col("deliv",            "配貨方式",                 90, "F"),
  AOD_col("temp",             "溫層",                    80, "F"),
  AOD_col("specNum",          "規格數字",                 90, "G", { num: true }),
  AOD_col("specUnit",         "規格單位",                 90, "G"),
  AOD_col("volumeUom",        "體積單位",                 90, "G"),
  AOD_col("volume",           "體積",                    80, "G", { num: true }),
  AOD_col("dimensionUom",     "尺寸單位",                 90, "G"),
  AOD_col("weightUom",        "重量單位",                 90, "G"),
  AOD_col("weightG",          "重量",                    80, "G", { num: true }),
  AOD_col("heightCm",         "高 (cm)",                  80, "G", { num: true }),
  AOD_col("widthCm",          "寬 (cm)",                  80, "G", { num: true }),
  AOD_col("lengthCm",         "長 (cm)",                  80, "G", { num: true }),
  AOD_col("unit",             "單位",                    70, "G"),
  AOD_col("saleCount",        "銷售入數",                 90, "G", { num: true }),
  AOD_col("boxCount",         "箱入數",                   80, "G", { num: true }),
  AOD_col("cartonWeight",     "箱重",                    90, "G"),
  AOD_col("specSheetUrl",     "規格表連結",               180, "H"),
  AOD_col("manufacturer",     "製造商",                  150, "H"),
  AOD_col("mfgPartNo",        "製造商品號",               150, "H", { mono: true }),
  AOD_col("infoNote",         "商品資訊備註",             200, "H"),
  AOD_col("estSales",         "預估業績/月",             120, "I", { num: true, nt: true }),
  AOD_col("origCost",         "原進價",                  100, "I", { num: true, nt: true }),
  AOD_col("promoCost",        "促進進價",                100, "I", { num: true, nt: true }),
  AOD_col("promoStart",       "促進開始",                110, "I", { mono: true }),
  AOD_col("promoEnd",         "促進結束",                110, "I", { mono: true }),
];

function AOD_buildGroups(cols) {
  const groups = [];
  let i = 0;
  while (i < cols.length) {
    const g = cols[i].group;
    let j = i;
    while (j < cols.length && cols[j].group === g) j++;
    groups.push({ group: g, colSpan: j - i });
    i = j;
  }
  return groups;
}

// Normalize each adj row to oracle-keyed fields based on source type
function AOD_normalizeRow(row, sourceType) {
  if (sourceType === "ADJ-A") {
    return {
      uid: row.uid,
      barcode: row.barcode,
      name: row.name,
      supplierName: row.newSupplierName,
      mainCat: row.mainCat,
      subCat: row.subCat,
      cost: row.newCost || "",
      taxRate: row.taxType,
      origCost: row.oldCost || "",
    };
  }
  if (sourceType === "ADJ-B") {
    return {
      uid: row.uid,
      barcode: row.barcode,
      name: row.name,
      mainCat: row.mainCat,
      subCat: row.subCat,
      listPrice: row.newPrice || "",
      cost: row.newCostExTax || "",
      taxRate: row.taxType,
      origCost: row.origCostExTax || "",
      promoEnd: row.newCostPromoEndDate || "",
    };
  }
  if (sourceType === "ADJ-C/D") {
    const types = Array.isArray(row.adjType) ? row.adjType : [];
    return {
      uid: row.uid,
      barcode: row.barcode,
      name: types.includes("infoName") ? (row.newName || row.productName) : row.productName,
      supplierName: row.supplierName,
      mainCat: row.mainCat,
      subCat: row.subCat,
      taxRate: types.includes("infoTaxRate") ? (row.newTaxRate || row.taxType) : row.taxType,
      temp: row.newTemp || "",
      specSummary: row.specSummary || "",
    };
  }
  return { uid: row.uid };
}

const AOD_renderCell = (row, c, idx) => {
  if (c.key === "#") return <span style={{ color: "var(--fg-3)", fontSize: 12 }}>{idx + 1}</span>;
  if (c.key === "twCode") return <span className="mono" style={{ fontSize: 12 }}>{`Uber TW DG ${row.barcode}`}</span>;
  const v = row[c.key];
  if (v === "" || v == null || v === 0) return <span className="cell-empty">—</span>;
  if (c.nt) return <span className="mono">{`NT$${Number(v).toLocaleString()}`}</span>;
  if (c.mono) return <span className="mono" style={{ fontSize: 12 }}>{v}</span>;
  return v;
};

// ── AdjOracleMetaCard ─────────────────────────────────────────────────────────
const AdjOracleMetaCard = ({ batch }) => {
  const [open, setOpen] = useState(false);
  if (!batch) return null;

  const approvedCount = batch.rows.filter(r => r.rowStatus === "adjApproved").length;
  const summary = `${batch.batchName} · ${batch.rows.length} 筆（${approvedCount} 筆已審核）`;

  return (
    <div className={`meta-card${open ? " meta-card--open" : ""}`}>
      <button
        className="meta-card__toggle"
        onClick={() => setOpen(v => !v)}
        aria-expanded={open}
      >
        <svg className="meta-card__chevron" width="14" height="14" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="9 18 15 12 9 6" />
        </svg>
        <span className="meta-card__summary">
          {open ? "批次資訊" : summary}
        </span>
      </button>

      {open && (
        <dl className="meta-card__body">
          <div className="meta-card__row">
            <dt>建立日期</dt>
            <dd><span className="mono">{batch.createdAt}</span></dd>
          </div>
          <div className="meta-card__row">
            <dt>更新時間</dt>
            <dd><span className="mono">{batch.updatedAt}</span></dd>
          </div>
          <div className="meta-card__row">
            <dt>商品調整所屬批次</dt>
            <dd><span className="mono">{batch.batchName}</span></dd>
          </div>
          <div className="meta-card__row">
            <dt>商品調整數</dt>
            <dd><b>{batch.rows.length}</b> 筆（已審核 <b>{approvedCount}</b> 筆）</dd>
          </div>
        </dl>
      )}
    </div>
  );
};

// ── AdjOracleDetail ───────────────────────────────────────────────────────────
const AdjOracleDetail = ({ batch, onBack }) => {
  const toast = useToast();
  const [mode, setMode] = useState("compact");
  const [exportPhase, setExportPhase] = useState(null);
  const [exportDone,  setExportDone]  = useState(0);

  const cols = mode === "compact" ? AOD_COMPACT_COLS : AOD_FULL_COLS;

  // Only export approved rows
  const approvedRows = batch.rows.filter(r => r.rowStatus === "adjApproved");
  const normalizedRows = approvedRows.map(r => AOD_normalizeRow(r, batch.sourceType));

  const doExport = () => {
    if (approvedRows.length === 0) {
      toast.push({ msg: "此批次無已審核品項，無法匯出", variant: "warn" });
      return;
    }
    const total = approvedRows.length;
    setExportDone(0);
    setExportPhase("parsing");
    runImportProgress(total, setExportDone, () => {
      setExportPhase("ok");
      setTimeout(() => setExportPhase(null), 1500);
    });
  };

  return (
    <>
      <PageHead
        crumbs={[
          { label: "商品調整" },
          { label: "商品主檔調整 Oracle 表", onClick: onBack },
          { label: batch.batchName, current: true },
        ]}
        title={batch.batchName}
        actions={
          <Button variant="primary" icon="download" onClick={doExport} disabled={exportPhase === "parsing"}>
            {exportPhase === "parsing" ? "匯出中…" : "匯出 Oracle"}
          </Button>
        }
      />
      <ImportBanner
        phase={exportPhase}
        parsingTitle="匯出準備中…"
        total={approvedRows.length}
        done={exportDone}
        okTitle="已匯出 Oracle CSV"
        okDesc=""
      />

      <AdjOracleMetaCard batch={batch} />

      <div className="card sku-card">
        <SkuToolbar>
          <ModeToggle mode={mode} onChange={setMode} />
          <span style={{ color: "var(--fg-2)", fontSize: 13, whiteSpace: "nowrap" }}>
            共 <b style={{ color: "var(--fg-1)" }}>{normalizedRows.length}</b> 筆已審核
            {batch.rows.length - approvedRows.length > 0 && (
              <span style={{ color: "var(--fg-3)" }}>（{batch.rows.length - approvedRows.length} 筆未審核，不匯出）</span>
            )}
          </span>
        </SkuToolbar>

        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr className="sku-tbl__thead-r1">
                {AOD_buildGroups(cols).map((g, i) => (
                  <th key={i} colSpan={g.colSpan}
                    className={`sku-tbl__th-group th-${['a','b','c','d','e','f','g','h'][i % 8]}`}>
                    {AOD_GROUP_LABELS[g.group]}
                  </th>
                ))}
              </tr>
              <tr className="sku-tbl__thead-r2">
                {cols.map(c => (
                  <th
                    key={c.key}
                    style={{ width: c.w, minWidth: c.w }}
                    className={[
                      c.sticky    ? "stk-l-0 center"       : "",
                      c.sticky2nd ? "stk-l-48 stk-shadow"  : "",
                      c.num ? "num" : "",
                    ].filter(Boolean).join(" ")}
                  >
                    {c.label}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {normalizedRows.map((row, idx) => (
                <tr key={row.uid || idx}>
                  {cols.map(c => (
                    <td
                      key={c.key}
                      className={[
                        c.sticky    ? "stk-l-0 center"       : "",
                        c.sticky2nd ? "stk-l-48 stk-shadow"  : "",
                        c.num ? "num" : "",
                      ].filter(Boolean).join(" ")}
                    >
                      {AOD_renderCell(row, c, idx)}
                    </td>
                  ))}
                </tr>
              ))}
              {normalizedRows.length === 0 && (
                <tr><td colSpan={cols.length}>
                  <div className="empty">
                    <div className="empty__icon"><Icon name="inbox" size={56} /></div>
                    <div className="empty__title">此批次無已審核品項</div>
                    <div className="empty__desc">只有審核通過的品項才會匯出至 Oracle。</div>
                  </div>
                </td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
};

Object.assign(window, { AdjOracleList: window.AdjOracleList, AdjOracleDetail });
