/* global React, Icon, Button, PortalSelect, Textarea, SlideDrawer, FormField, FormFieldVal, FormSectionDivider,
   CellDisplay, TableGroupHeader, ModeToggle, SkuToolbar, Pager, RowActions, Dialog, useToast,
   useSortableTable, PageHead, FilterBar, EmptyState, PAGE_SIZES, UserChip,
   VD_COLS, VD_GROUP_LABELS, VD_UID, SOURCES */
// 廠商配送資料（配送資料設定）L1 — 跨廠商平坦清單 + Drawer 編輯（spec 24）
// 沿用 eo 的清單/Drawer 殼，但無審核（無 useSubmissionModel / 狀態 / 線別 / applicant）。

const { useState, useMemo } = React;

// ── 欄位組裝（識別欄 + 配送欄 + 操作；ModeToggle 機制比照 eo）─────────────────
const VD_LEADING_COLS = [
  { key: "vendorNo",    label: "廠商編號", w: 100, group: "ID", leading: true, sticky: true, mono: true },
  { key: "vendorShort", label: "廠商簡稱", w: 130, group: "ID", leading: true },
];
const VD_LIST_ACTION_COL = { key: "_action", label: "操作", w: 110, group: "CTRL", actionCol: true };
const VD_LIST_GROUP_LABELS = { ID: "廠商", ...VD_GROUP_LABELS, CTRL: "操作" };
// 精選欄（最小可辨識一條配送規則的欄集；其餘細節留給 Drawer）
const VD_COMPACT_KEYS = ["delivMoa", "delivCycle", "delivStores", "delivDays"];

const VENDOR_DELIV_NUM_W = 0;

// ── Drawer 內單一欄位控制項 ──────────────────────────────────────────────────
const VdFieldControl = ({ field, value, onChange }) => {
  if (field.formula) {
    return <FormFieldVal mono={field.mono}>{value || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>;
  }
  if (field.type === "select") {
    const opts = (SOURCES[field.source] || []).map(o => ({ value: o, label: o }));
    return <PortalSelect value={value || ""} options={opts} onChange={onChange}
             triggerClassName="field-trigger" placeholder="選擇…" />;
  }
  if (field.type === "num") {
    return <input className="field mono" type="number" value={value ?? ""} placeholder="0"
             onChange={e => onChange(e.target.value === "" ? null : +e.target.value)} />;
  }
  if (field.type === "text") {
    return <Textarea rows={2} value={value || ""}
             placeholder={field.placeholder || ""} onChange={e => onChange(e.target.value)} />;
  }
  // str
  return <input className="field" value={value || ""} placeholder={field.placeholder || ""}
           onChange={e => onChange(e.target.value)} />;
};

// ── 編輯 / 新增 Drawer ───────────────────────────────────────────────────────
const VendorDelivDrawer = ({ row: rowProp, isNew, vendorOptions, onClose, onSave }) => {
  const { push: toast } = useToast();
  const [row, setRow] = useState(() => ({ ...rowProp }));
  const [changed, setChanged] = useState(new Set());
  const [showErr, setShowErr] = useState(false);

  const patch = (key, val) => {
    setRow(prev => ({ ...prev, [key]: val }));
    setChanged(prev => new Set(prev).add(key));
  };
  const isDirty = changed.size > 0;

  // 必填：新增時須選廠商；配送週期必填
  const vendorErr = isNew && !row.vendorNo;
  const cycleErr  = !row.delivCycle;
  const hasErr    = vendorErr || cycleErr;

  const handleSave = (close) => {
    setShowErr(true);
    if (hasErr) { toast({ kind: "warning", msg: "請填寫廠商與配送週期" }); return; }
    onSave(row, isNew);
    close();
    toast({ kind: "success", msg: isNew ? "已新增配送規則" : "配送規則已更新" });
  };

  const vendorLabel = vendorOptions.find(o => o.value === row.vendorNo)?.label || row.vendorNo || "—";
  const groups = [["A", "訂購門檻"], ["B", "適用範圍"], ["C", "配送與退貨"]];

  return (
    <SlideDrawer
      title={isNew ? "新增配送規則" : `編輯配送規則 · ${vendorLabel}`}
      isDirty={isDirty}
      dirtyCount={changed.size}
      dirtyMsg={`有 ${changed.size} 個欄位已修改，關閉後變更將會遺失。`}
      onClose={onClose}
      foot={(tryClose) => (<>
        <Button variant="text" onClick={tryClose}>取消</Button>
        <Button variant="primary" onClick={() => handleSave(onClose)}>{isNew ? "新增" : "儲存"}</Button>
      </>)}
    >
      {/* 廠商：新增可選、編輯鎖定（前置主體欄位，不另立區塊標題避免與欄位名重複）*/}
      <div className="drawer-grid">
        <FormField label="廠商" required={isNew} locked={!isNew} error={showErr && vendorErr ? "必選" : null}>
          {isNew
            ? <PortalSelect value={row.vendorNo || ""} options={vendorOptions}
                onChange={v => patch("vendorNo", v)} triggerClassName="field-trigger" placeholder="選擇廠商…" />
            : <FormFieldVal mono>{vendorLabel}</FormFieldVal>}
        </FormField>
      </div>

      {/* A / B / C 配送欄位 */}
      {groups.map(([g, label]) => (
        <React.Fragment key={g}>
          <FormSectionDivider badge={g} label={label} />
          <div className="drawer-grid">
            {VD_COLS.filter(c => c.group === g).map(col => (
              <FormField key={col.key} label={col.label}
                required={col.key === "delivCycle"} locked={col.field.formula}
                error={showErr && col.key === "delivCycle" && cycleErr ? "必填" : null}
                style={col.key === "note" || col.key === "delivMoqGroup" || col.key === "delivStores" ? { gridColumn: "span 2" } : null}>
                <VdFieldControl field={col.field} value={row[col.key]} onChange={v => patch(col.key, v)} />
              </FormField>
            ))}
          </div>
        </React.Fragment>
      ))}
    </SlideDrawer>
  );
};

// ── L1 清單 ──────────────────────────────────────────────────────────────────
const VendorDeliveryList = ({ deliveries, vendors, canEdit, onSaveRow, onDeleteRow, sectionLabel, titleLabel }) => {
  const { push: toast } = useToast();
  const [search,     setSearch]     = useState("");
  const [fVendor,    setFVendor]    = useState([]);
  const [fCycle,     setFCycle]     = useState([]);
  const [fDefective, setFDefective] = useState([]);
  const [fGoods,     setFGoods]     = useState([]);
  const [page,       setPage]       = useState(1);
  const [pageSize,   setPageSize]   = useState(PAGE_SIZES[0]);
  const [colMode,    setColMode]    = useState("compact");
  const [drawer,     setDrawer]     = useState(null); // null | { row, isNew }
  const [deleteRow,  setDeleteRow]  = useState(null);
  const { SortHead, applySortTo }   = useSortableTable("vendorNo", "asc");

  // 廠商編號 → 簡稱
  const vendorShortOf = useMemo(() => {
    const m = {};
    vendors.forEach(v => { m[v.vendorNo] = v.vendorShort; });
    return m;
  }, [vendors]);

  const vendorOptions = useMemo(() =>
    [...vendors].sort((a, b) => a.vendorNo.localeCompare(b.vendorNo))
      .map(v => ({ value: v.vendorNo, label: `${v.vendorNo} · ${v.vendorShort}` })),
    [vendors]);

  // 清單列 = 配送列 + 廠商簡稱
  const rows = useMemo(() =>
    deliveries.map(d => ({ ...d, vendorShort: vendorShortOf[d.vendorNo] || "" })),
    [deliveries, vendorShortOf]);

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return rows.filter(r => {
      if (q && !(`${r.vendorNo} ${r.vendorShort} ${r.delivStores || ""}`.toLowerCase().includes(q))) return false;
      if (fVendor.length    && !fVendor.includes(r.vendorNo))               return false;
      if (fCycle.length     && !fCycle.includes(r.delivCycle))             return false;
      if (fDefective.length && !fDefective.includes(r.defectiveHandling))  return false;
      if (fGoods.length     && !fGoods.includes(r.applicableGoods))        return false;
      return true;
    });
  }, [rows, search, fVendor, fCycle, fDefective, fGoods]);

  const sorted = useMemo(() => applySortTo(filtered, (r, key) => r[key] ?? ""), [filtered, applySortTo]);
  const paged  = sorted.slice((page - 1) * pageSize, page * pageSize);

  const dataCols = useMemo(() => {
    const deliv = colMode === "compact"
      ? VD_COLS.filter(c => VD_COMPACT_KEYS.includes(c.key))
      : VD_COLS;
    return [...VD_LEADING_COLS, ...deliv, ...(canEdit ? [VD_LIST_ACTION_COL] : [])];
  }, [colMode, canEdit]);

  const totalWidth = dataCols.reduce((s, c) => s + c.w, 0);

  const getActions = (r) => canEdit
    ? [
        { label: "編輯", onClick: () => setDrawer({ row: r, isNew: false }) },
        { label: "刪除", danger: true, onClick: () => setDeleteRow(r) },
      ]
    : [{ label: "檢視", onClick: () => setDrawer({ row: r, isNew: false }) }];

  const renderColTh = (col) => (
    <th key={col.key} style={{
      width: col.w, minWidth: col.w, whiteSpace: "nowrap",
      ...(col.sticky ? { position: "sticky", left: 0, zIndex: 2, background: "var(--gray-50)" } : null),
      ...(col.actionCol ? { textAlign: "center" } : null),
    }}>
      {col.actionCol ? col.label : <SortHead colKey={col.key} label={col.label} />}
    </th>
  );

  const renderCell = (col, r) => {
    if (col.key === "vendorNo") return (
      <td key={col.key} className="mono" style={{ position: "sticky", left: 0, zIndex: 1, background: "var(--bg-surface)", boxShadow: "2px 0 4px rgba(0,0,0,.06)" }}>{r.vendorNo}</td>
    );
    if (col.key === "vendorShort") return <td key={col.key}>{r.vendorShort || <span style={{ color: "var(--fg-4)" }}>—</span>}</td>;
    if (col.actionCol) return <td key={col.key} className="center"><RowActions actions={getActions(r)} /></td>;
    return <td key={col.key}><CellDisplay field={col.field} value={r[col.key]} row={r} /></td>;
  };

  const emptyRow = () => ({ uid: VD_UID(), vendorNo: "", delivMoa: null, delivMoq: null, delivMoqUnit: "", delivMoqGroup: "", applicableGoods: "全部商品", applicableSkus: "", defectiveHandling: "", delivCycle: "", delivStores: "", delivDays: "", delivDaysCode: "", note: "" });

  return (
    <>
      <PageHead
        section={sectionLabel}
        title={titleLabel}
        subtitle="設定各廠商的訂購門檻、適用範圍與配送/退貨規則。"
        actions={canEdit && (
          <Button variant="primary" icon="plus" onClick={() => setDrawer({ row: emptyRow(), isNew: true })}>新增配送規則</Button>
        )}
      />

      <FilterBar
        filters={[
          { type: "search", placeholder: "搜尋廠商編號、簡稱、配送門店…", value: search, onChange: v => { setSearch(v); setPage(1); } },
          { type: "chip", label: "廠商", multi: true, value: fVendor, options: vendorOptions, onChange: v => { setFVendor(v); setPage(1); } },
          { type: "chip", label: "配送週期", multi: true, value: fCycle, options: (SOURCES.delivCycle || []).map(o => ({ value: o, label: o })), onChange: v => { setFCycle(v); setPage(1); } },
          { type: "chip", label: "瑕疵品處理", multi: true, value: fDefective, options: (SOURCES.defectiveHandling || []).map(o => ({ value: o, label: o })), onChange: v => { setFDefective(v); setPage(1); } },
          { type: "chip", label: "適用商品", multi: true, value: fGoods, options: (SOURCES.applicableGoods || []).map(o => ({ value: o, label: o })), onChange: v => { setFGoods(v); setPage(1); } },
        ]}
      />

      <div className="card">
        <SkuToolbar>
          <ModeToggle mode={colMode} onChange={setColMode} />
          <span style={{ fontSize: "var(--fs-13)", color: "var(--fg-2)", flexShrink: 0, marginLeft: 12 }}>
            共 <b style={{ color: "var(--fg-1)" }}>{sorted.length}</b> 筆
          </span>
        </SkuToolbar>

        <div className="tbl-wrap">
          <table className="tbl" style={{ borderCollapse: "separate", borderSpacing: 0, minWidth: totalWidth }}>
            <thead>
              <TableGroupHeader cols={dataCols} groupLabels={VD_LIST_GROUP_LABELS} />
              <tr>{dataCols.map(renderColTh)}</tr>
            </thead>
            <tbody>
              {paged.length === 0 && (
                <tr>
                  <td colSpan={dataCols.length}>
                    <div className="empty" style={{ padding: "40px 20px" }}>
                      <div className="empty__icon"><Icon name="truck" size={36} /></div>
                      <div className="empty__title">沒有符合條件的配送規則</div>
                      <div className="empty__desc">試試清除篩選條件{canEdit ? "，或點右上角「新增配送規則」" : ""}。</div>
                    </div>
                  </td>
                </tr>
              )}
              {paged.map(r => (
                <tr key={r.uid}>{dataCols.map(col => renderCell(col, r))}</tr>
              ))}
            </tbody>
          </table>
        </div>

        <Pager total={sorted.length} page={page} pageSize={pageSize}
          pageSizeOptions={PAGE_SIZES} onPage={setPage}
          onPageSize={p => { setPageSize(p); setPage(1); }} />
      </div>

      {drawer && (
        <VendorDelivDrawer
          row={drawer.row} isNew={drawer.isNew} vendorOptions={vendorOptions}
          onClose={() => setDrawer(null)}
          onSave={(saved, isNew) => { onSaveRow(saved, isNew); setDrawer(null); }}
        />
      )}

      <Dialog
        open={!!deleteRow}
        title="刪除配送規則"
        onClose={() => setDeleteRow(null)}
        footer={<>
          <Button variant="default" onClick={() => setDeleteRow(null)}>取消</Button>
          <Button variant="danger" onClick={() => {
            onDeleteRow(deleteRow.uid);
            toast({ kind: "warning", msg: `已刪除「${deleteRow.vendorShort || deleteRow.vendorNo}」的一筆配送規則` });
            setDeleteRow(null);
          }}>確認刪除</Button>
        </>}
      >
        <div style={{ fontSize: "var(--fs-14)", color: "var(--fg-1)", lineHeight: 1.6 }}>
          確定刪除「{deleteRow?.vendorShort || deleteRow?.vendorNo}」配送門店「{deleteRow?.delivStores || "—"}」這條配送規則？此操作無法復原。
        </div>
      </Dialog>
    </>
  );
};

Object.assign(window, { VendorDeliveryList });
