/* global React, Icon, Button, Tag, Dialog, PageHead, FilterBar, Pager, RowActions, InfoNote, useToast, PAGE_SIZES, useSortableTable, SEED_FORMS, PRODUCT_MASTER, PRICE_HISTORY, ADJ_BATCHES */
// 廠商基礎資料 L1 — 廠商列表

const { useState, useMemo } = React;

// ── Oracle 狀態顯示（使用 Tag，對齊全站視覺語言）────────────────────────────
const OracleStatusCell = ({ status }) => {
  if (status === "synced")    return <Tag status="oracleSynced" />;
  if (status === "pending")   return <Tag status="oraclePending" />;
  if (status === "not_found") return <Tag status="oracleNotFound" />;
  return <span className="cell-em">—</span>;
};

// ── 狀態碼的語意排序順序（狀態欄非字母序，依顯示標籤的邏輯遞進排序）────────────
// Oracle 建檔：未填寫 → 待同步 → 查無資料 → 已建檔
const ORACLE_SORT_ORDER = { empty: 0, pending: 1, not_found: 2, synced: 3 };
// 廠商狀態：草稿 → 合作中 → 停止合作（對齊 vendorTagLabel 的顯示）
const VENDOR_STATUS_SORT_ORDER = { draft: 0, active: 1, suspended: 2 };
const vendorSortVal = (row, key) => {
  if (key === "oracleReady")  return ORACLE_SORT_ORDER[row.oracleReady] ?? -1;
  if (key === "vendorStatus") return VENDOR_STATUS_SORT_ORDER[row.formStatus === "draft" ? "draft" : row.vendorStatus] ?? -1;
  return row[key] ?? "";
};

// ── 刪除保護檢查 ─────────────────────────────────────────────────────────────
const checkVendorDeleteGuard = (vendor) => {
  if (vendor.oracleReady === "synced") return "oracle";
  const no = vendor.vendorNo;
  const inForms  = (typeof SEED_FORMS  !== "undefined") && SEED_FORMS.some(f => f.items && f.items.some(i => i.supplierNo === no));
  const inMaster = (typeof PRODUCT_MASTER !== "undefined") && PRODUCT_MASTER.some(p => p.supplierNo === no);
  const inHist   = (typeof PRICE_HISTORY  !== "undefined") && PRICE_HISTORY.some(p => p.supplierNo === no);
  const inAdj    = (typeof ADJ_BATCHES    !== "undefined") && ADJ_BATCHES.some(b => b.rows && b.rows.some(i => i.supplierNo === no || i.oldSupplierNo === no || i.newSupplierNo === no));
  if (inForms || inMaster || inHist || inAdj) return "referenced";
  return null;
};

// ── VendorList ───────────────────────────────────────────────────────────────
const VendorList = ({ vendors, canEdit, onAdd, onEdit, onView, onDelete, onSuspend, sectionLabel, titleLabel }) => {
  const { push: toast } = useToast();
  const [fText,       setFText]       = useState("");
  const [fStatus,     setFStatus]     = useState([]);
  const [fOracle,     setFOracle]     = useState([]);
  const [deleteDialog, setDeleteDialog] = useState(null); // null | { vendor, guard }
  const [page,        setPage]        = useState(1);
  const [pageSize,    setPageSize]    = useState(PAGE_SIZES[0]);
  const { SortHead, applySortTo } = useSortableTable("vendorNo", "asc");

  // ── Tag 計算 ─────────────────────────────────────────────────────────────────
  const vendorTagStatus = (v) => {
    if (v.formStatus === "draft")       return "vendorDraft";
    if (v.vendorStatus === "suspended") return "vendorSuspended";
    return "vendorActive";
  };

  const vendorTagLabel = (v) => {
    if (v.formStatus === "draft")       return "草稿";
    if (v.vendorStatus === "suspended") return "停止合作";
    return "合作中";
  };

  // ── 篩選 ─────────────────────────────────────────────────────────────────────
  const filtered = useMemo(() => {
    let rows = vendors;
    if (fText.trim()) {
      const q = fText.trim().toLowerCase();
      rows = rows.filter(v =>
        v.vendorNo.toLowerCase().includes(q) ||
        v.vendorShort.toLowerCase().includes(q) ||
        v.vendorName.toLowerCase().includes(q)
      );
    }
    if (fStatus.length) {
      rows = rows.filter(v => fStatus.includes(vendorTagLabel(v)));
    }
    if (fOracle.length) {
      const ORACLE_MAP = { "已建檔": "synced", "待同步": "pending", "查無資料": "not_found", "未填寫": "empty" };
      rows = rows.filter(v => fOracle.some(label => ORACLE_MAP[label] === v.oracleReady));
    }
    return applySortTo(rows, vendorSortVal);
  }, [vendors, fText, fStatus, fOracle, applySortTo]);

  const paged = filtered.slice((page - 1) * pageSize, page * pageSize);

  // ── 列操作 ───────────────────────────────────────────────────────────────────
  const getActions = (vendor) => {
    if (canEdit) {
      return [
        { label: "編輯", onClick: () => onEdit(vendor) },
        { label: "刪除", danger: true, onClick: () => setDeleteDialog({ vendor, guard: checkVendorDeleteGuard(vendor) }) },
      ];
    }
    return [{ label: "檢視", onClick: () => onView(vendor) }];
  };

  // ── 刪除確認 ─────────────────────────────────────────────────────────────────
  const confirmDelete = () => {
    onDelete(deleteDialog.vendor);
    toast({ msg: `廠商「${deleteDialog.vendor.vendorShort}」已刪除`, kind: "success" });
    setDeleteDialog(null);
  };

  // 無法刪除時的替代動作：改為停止合作（僅對尚未停用的廠商提供）
  const confirmSuspend = () => {
    onSuspend(deleteDialog.vendor);
    toast({ msg: `廠商「${deleteDialog.vendor.vendorShort}」已改為停止合作`, kind: "success" });
    setDeleteDialog(null);
  };

  return (
    <>
      <PageHead
        section={sectionLabel}
        title={titleLabel}
        subtitle="管理所有合作廠商的基礎資料，含識別、聯絡、訂購條件、財務帳務與配送規則。"
        actions={canEdit && (
          <Button variant="primary" icon="plus" onClick={onAdd}>新增廠商</Button>
        )}
      />

      <FilterBar
        filters={[
          { type: "search", placeholder: "搜尋廠商代號 / 簡稱 / 公司全名…", value: fText, onChange: v => { setFText(v); setPage(1); } },
          { label: "廠商狀態", value: fStatus, options: ["草稿", "合作中", "停止合作"], onChange: v => { setFStatus(v); setPage(1); }, multi: true },
          { label: "Oracle 建檔", value: fOracle, options: ["已建檔", "待同步", "查無資料", "未填寫"], onChange: v => { setFOracle(v); setPage(1); }, multi: true },
        ]}
      />

      <div className="card">
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th style={{ width: 100 }}><SortHead colKey="vendorNo"    label="廠商代號" /></th>
                <th style={{ width: 120 }}><SortHead colKey="vendorShort" label="簡稱" /></th>
                <th><SortHead colKey="vendorName" label="公司全名" /></th>
                <th style={{ width: 110 }}><SortHead colKey="vendorStatus" label="廠商狀態" /></th>
                <th style={{ width: 110 }}><SortHead colKey="oracleReady" label="Oracle 建檔" /></th>
                <th className="center" style={{ width: 100 }}>功能</th>
              </tr>
            </thead>
            <tbody>
              {paged.length === 0 ? (
                <tr>
                  <td colSpan={6} style={{ textAlign: "center", color: "var(--fg-4)", padding: "40px 0", fontSize: "var(--fs-13)" }}>
                    查無符合條件的廠商
                  </td>
                </tr>
              ) : paged.map(v => (
                <tr key={v.uid}>
                  <td className="mono" style={{ fontSize: "var(--fs-12)" }}>{v.vendorNo}</td>
                  <td>{v.vendorShort || <span className="cell-em">—</span>}</td>
                  <td>{v.vendorName  || <span className="cell-em">—</span>}</td>
                  <td><Tag status={vendorTagStatus(v)} /></td>
                  <td><OracleStatusCell status={v.oracleReady} /></td>
                  <td className="center">
                    <RowActions actions={getActions(v)} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <Pager total={filtered.length} page={page} pageSize={pageSize}
          onPageChange={setPage} onSizeChange={s => { setPageSize(s); setPage(1); }} />
      </div>

      {/* 刪除 — 無法刪除（已同步 Oracle / 有關聯資料），依是否已停用分流文案與動作 */}
      {(deleteDialog?.guard === "oracle" || deleteDialog?.guard === "referenced") && (() => {
        const v = deleteDialog.vendor;
        const isSuspended = v.vendorStatus === "suspended";
        // 「改為停止合作」只對目前「合作中」的廠商有意義：已停用無下一步、草稿尚未開始合作
        const canSuspend = !isSuspended && v.formStatus !== "draft";
        const who = `${v.vendorShort}（${v.vendorNo}）`;
        const reason = deleteDialog.guard === "oracle"
          ? "已同步至 Oracle"
          : "已有關聯資料（商品主檔 / 新商品建立單 / 轉廠商調整）";
        const body = isSuspended
          ? `廠商「${who}」已停止合作，且${reason}，系統保留紀錄，無法刪除。`
          : `廠商「${who}」${reason}，無法直接刪除。`;
        const footer = canSuspend
          ? <>
              <Button variant="text" onClick={() => setDeleteDialog(null)}>取消</Button>
              <Button variant="primary" onClick={confirmSuspend}>改為停止合作</Button>
            </>
          : <Button variant="primary" onClick={() => setDeleteDialog(null)}>我知道了</Button>;
        return (
          <Dialog open title="無法刪除廠商" onClose={() => setDeleteDialog(null)} footer={footer}>
            <p style={{ fontSize: "var(--fs-13)", color: "var(--fg-1)", margin: canSuspend ? "0 0 10px" : 0 }}>
              {body}
            </p>
            {canSuspend && <InfoNote>若只需停用此廠商，可改為「停止合作」。</InfoNote>}
          </Dialog>
        );
      })()}

      {/* 刪除 — danger 二次確認 */}
      {deleteDialog?.guard === null && (
        <Dialog open title="刪除廠商" onClose={() => setDeleteDialog(null)}
          footer={<>
            <Button variant="text" onClick={() => setDeleteDialog(null)}>取消</Button>
            <Button variant="danger" onClick={confirmDelete}>刪除廠商</Button>
          </>}>
          <p style={{ fontSize: "var(--fs-13)", color: "var(--fg-1)", margin: 0 }}>
            確定要刪除「{deleteDialog.vendor.vendorShort}（{deleteDialog.vendor.vendorNo}）」？此操作無法復原。
          </p>
        </Dialog>
      )}
    </>
  );
};

Object.assign(window, { VendorList, OracleStatusCell });
