/* global React, Icon, Button, Field, NumInput, Tag, STATUS, PageHead, SectionCard, FormField, FormFieldVal, FormSectionDivider, PortalSelect, CellDisplay, CellEditor, TableGroupHeader, EmptyState, SkuToolbar, DeleteRowBtn, useToast, SOURCES, VD_COLS, VD_GROUP_LABELS, VD_UID */
// 廠商基礎資料 L2 — 廠商編輯頁（新增 / 編輯 / 唯讀）

const { useState, useMemo, useCallback, useEffect } = React;

// Oracle 建檔狀態 → 顯示文字（沿用 STATUS 既有 label，唯一來源；唯讀欄位以純文字呈現，不用 Tag）
const oracleStatusLabel = (s) => {
  const key = { synced: "oracleSynced", pending: "oraclePending", not_found: "oracleNotFound" }[s];
  return key ? STATUS[key].label : "—";
};

// 配送資料欄定義 VD_COLS / VD_GROUP_LABELS / VD_UID 已提升至 data.jsx 全域，
// 與「廠商配送資料」獨立模組（vendor-delivery.jsx）共用同一份定義。

// RadioGroup → 已提升到 primitives.jsx（2026-06-02），改從 window 取用

// ── VendorDetail ──────────────────────────────────────────────────────────────
const VendorDetail = ({
  vendor: vendorProp,
  deliveries: deliveriesProp,
  allVendors,
  readOnly,
  onBack,
  onSaveDraft,
  onSubmit,
  onDirtyChange,
}) => {
  const isNew = !vendorProp || vendorProp.uid === "__new__";
  const { push: toast } = useToast();

  const [vendor,     setVendor]     = useState(() => isNew
    ? (typeof emptyVendor !== "undefined" ? emptyVendor() : {})
    : { ...vendorProp }
  );
  const [deliveries, setDeliveries] = useState(() =>
    (deliveriesProp || []).filter(d => !isNew && d.vendorNo === vendorProp.vendorNo)
  );
  const [dirty,      setDirty]      = useState(false);
  const [errors,     setErrors]     = useState({});
  const [showErrors, setShowErrors] = useState(false);

  const patch = useCallback((key, val) => {
    setVendor(prev => ({ ...prev, [key]: val }));
    setDirty(true);
    if (errors[key]) setErrors(prev => { const n = { ...prev }; delete n[key]; return n; });
  }, [errors]);

  // 將本地 dirty 上報給 app 的全域 isDirty，導覽守衛（guardedNav）才會在未儲存時攔截；
  // 卸載時重設為 false（與 co-detail / adj-detail 同一模式）
  useEffect(() => { onDirtyChange?.(dirty); }, [dirty, onDirtyChange]);
  useEffect(() => () => onDirtyChange?.(false), [onDirtyChange]);

  // ── 驗證 ────────────────────────────────────────────────────────────────────
  const validate = () => {
    const errs = {};
    if (!vendor.vendorNo || !vendor.vendorNo.trim()) errs.vendorNo = "廠商代號必填";
    else {
      const dup = (allVendors || []).find(v => v.vendorNo === vendor.vendorNo.trim() && v.uid !== vendor.uid);
      if (dup) errs.vendorNo = "此廠商代號已存在";
    }
    if (!vendor.vendorShort || !vendor.vendorShort.trim()) errs.vendorShort = "簡稱必填";
    if (!vendor.vendorStatus) errs.vendorStatus = "廠商狀態必填";
    return errs;
  };

  // ── CTA ─────────────────────────────────────────────────────────────────────
  const handleSaveDraft = () => {
    const updated = { ...vendor, formStatus: "draft" };
    onSaveDraft(updated, deliveries, isNew);
    setDirty(false);
    toast({ msg: "草稿已儲存", kind: "success" });
  };

  const handleSubmit = () => {
    const errs = validate();
    if (Object.keys(errs).length) { setErrors(errs); setShowErrors(true); return; }
    const updated = { ...vendor, formStatus: "active" };
    onSubmit(updated, deliveries, isNew);
    toast({ msg: isNew ? `廠商「${vendor.vendorShort}」已建立` : `廠商「${vendor.vendorShort}」已更新`, kind: "success" });
  };

  // ── 配送資料 ─────────────────────────────────────────────────────────────────
  const addDelivRow = () => {
    setDeliveries(prev => [...prev, {
      uid: VD_UID(), vendorNo: vendor.vendorNo || "",
      delivMoa: "", delivMoq: "", delivMoqUnit: "", delivMoqGroup: "",
      applicableGoods: "全部商品", applicableSkus: "",
      defectiveHandling: "退貨", delivCycle: "", delivStores: "", delivDays: "", delivDaysCode: "", note: "",
    }]);
    setDirty(true);
  };

  const patchDeliv = (uid, key, val) => {
    setDeliveries(prev => prev.map(d => d.uid === uid ? { ...d, [key]: val } : d));
    setDirty(true);
  };

  const deleteDeliv = (uid) => {
    setDeliveries(prev => prev.filter(d => d.uid !== uid));
    setDirty(true);
  };

  // ── 輔助 ─────────────────────────────────────────────────────────────────────
  const fv = (key) => (vendor[key] != null ? vendor[key] : "");
  const oracleAllFilled = vendor.oracleVendorNo && vendor.oracleVendorName && vendor.oracleAddressTable;

  const titleTag = () => {
    if (vendor.formStatus === "draft")      return <Tag status="vendorDraft" />;
    if (vendor.vendorStatus === "suspended") return <Tag status="vendorSuspended" />;
    return <Tag status="vendorActive" />;
  };

  // ── Render ───────────────────────────────────────────────────────────────────
  return (
    <>
      <PageHead
        crumbs={[
          { label: "廠商" },
          { label: "廠商基礎資料", onClick: onBack },
          { label: isNew ? "新增廠商" : vendor.vendorShort, current: true },
        ]}
        title={
          <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
            {isNew ? "新增廠商" : vendor.vendorShort}
            {!isNew && titleTag()}
          </span>
        }
        dirty={dirty}
        actions={readOnly
          ? <Button variant="default" onClick={onBack}>關閉</Button>
          : <>
              <Button variant="text" onClick={onBack}>取消</Button>
              <Button variant="default" onClick={handleSaveDraft}>儲存草稿</Button>
              <Button variant="primary" onClick={handleSubmit}>送出</Button>
            </>
        }
      />

      {/* ── Card 1：廠商基礎資料 ─────────────────────────────────── */}
      <SectionCard title="廠商基礎資料" defaultOpen>
        <div className="form-grid">

          {/* A. 識別 */}
          <FormSectionDivider badge="A" label="識別" first />

          <FormField label="廠商代號" required={!readOnly} locked={!isNew && !readOnly}
            error={showErrors ? errors.vendorNo : null}>
            {(readOnly || !isNew)
              ? <FormFieldVal mono>{fv("vendorNo") || "—"}</FormFieldVal>
              : <Field value={fv("vendorNo")} onChange={e => patch("vendorNo", e.target.value)}
                  placeholder="請輸入 ERP 廠商代號" error={showErrors && !!errors.vendorNo} />
            }
          </FormField>

          <FormField label="廠商狀態" required={!readOnly} error={showErrors ? errors.vendorStatus : null}>
            {readOnly
              ? <FormFieldVal>{vendor.vendorStatus === "suspended" ? "停止合作" : "合作中"}</FormFieldVal>
              : <PortalSelect value={fv("vendorStatus")}
                  options={[{ value: "active", label: "合作中" }, { value: "suspended", label: "停止合作" }]}
                  onChange={v => patch("vendorStatus", v)}
                  triggerClassName={"field-trigger" + (showErrors && errors.vendorStatus ? " field-trigger--error" : "")}
                  placeholder="請選擇" />
            }
          </FormField>

          <FormField label="簡稱" required={!readOnly} error={showErrors ? errors.vendorShort : null}>
            {readOnly
              ? <FormFieldVal>{fv("vendorShort") || "—"}</FormFieldVal>
              : <Field value={fv("vendorShort")} onChange={e => patch("vendorShort", e.target.value)}
                  error={showErrors && !!errors.vendorShort} />
            }
          </FormField>

          <FormField label="公司全名">
            {readOnly
              ? <FormFieldVal>{fv("vendorName") || "—"}</FormFieldVal>
              : <Field value={fv("vendorName")} onChange={e => patch("vendorName", e.target.value)} />
            }
          </FormField>

          {/* B. Oracle 系統 */}
          <FormSectionDivider badge="B" label="Oracle 系統" />

          {/* 可編輯的廠商編號在左、唯讀建檔狀態在右：先輸入 key → 看建檔結果 */}
          <FormField label="Oracle 廠商編號"
            hint={!readOnly ? "系統以此為 key 去 Oracle 查詢，填入後待下次同步時回填名稱與地表" : undefined}>
            {readOnly
              ? <FormFieldVal mono>{fv("oracleVendorNo") || "—"}</FormFieldVal>
              : <Field value={fv("oracleVendorNo")} onChange={e => patch("oracleVendorNo", e.target.value)}
                  placeholder="請輸入 Oracle 廠商編號" />
            }
          </FormField>

          {/* 建檔狀態以唯讀欄位呈現（純文字，不用 Tag）；同步說明以欄位備註 hint 顯示 */}
          <FormField label="Oracle 已建檔" locked
            hint={oracleAllFilled
              ? "三個 Oracle 欄位皆已填寫，待下次同步比對後自動更新建檔狀態。"
              : "由系統同步比對後自動更新，不可手動修改。"}>
            <FormFieldVal>{oracleStatusLabel(vendor.oracleReady)}</FormFieldVal>
          </FormField>

          <FormField label="Oracle 廠商名稱" locked>
            <FormFieldVal>{fv("oracleVendorName") || "—"}</FormFieldVal>
          </FormField>

          <FormField label="Oracle 廠商地表" locked>
            <FormFieldVal mono>{fv("oracleAddressTable") || "—"}</FormFieldVal>
          </FormField>

          <FormField label="下單分流類型" locked>
            <FormFieldVal>{fv("outputType") || "—"}</FormFieldVal>
          </FormField>

          {/* C. 銷售地區 */}
          <FormSectionDivider badge="C" label="銷售地區" />

          <FormField label="銷售地區群組">
            {readOnly
              ? <FormFieldVal>{(vendor.districtGroup || []).join("、") || "—"}</FormFieldVal>
              : <PortalSelect multi value={vendor.districtGroup || []}
                  options={SOURCES.districtGroup || []}
                  onChange={v => patch("districtGroup", v)}
                  triggerClassName="field-trigger" placeholder="請選擇" />
            }
          </FormField>

          <FormField label="銷售地區門店">
            {readOnly
              ? <FormFieldVal>{(vendor.districtStore || []).join("、") || "—"}</FormFieldVal>
              : <PortalSelect multi value={vendor.districtStore || []}
                  options={SOURCES.districtStore || []}
                  onChange={v => patch("districtStore", v)}
                  triggerClassName="field-trigger" placeholder="請選擇" />
            }
          </FormField>

          {/* D. 聯絡資訊 */}
          <FormSectionDivider badge="D" label="聯絡資訊" />

          {[
            ["taxId",       "統一編號",      false, true],
            ["tel1",        "電話",          false, false],
            ["emailNorth",  "E-mail（北區）", false, false],
            ["emailCentral","E-mail（中區）", false, false],
            ["owner",       "負責人",        false, false],
            ["contact1",    "聯絡人",        false, false],
          ].map(([key, label, , mono]) => (
            <FormField key={key} label={label}>
              {readOnly
                ? <FormFieldVal mono={mono}>{fv(key) || "—"}</FormFieldVal>
                : <Field value={fv(key)} onChange={e => patch(key, e.target.value)} />
              }
            </FormField>
          ))}

          {[["address1","聯絡地址一"], ["address2","聯絡地址二"],
            ["billAddress1","帳單地址一"], ["billAddress2","帳單地址二"]
          ].map(([key, label]) => (
            <FormField key={key} label={label} className="form-grid__full">
              {readOnly
                ? <FormFieldVal>{fv(key) || "—"}</FormFieldVal>
                : <Field value={fv(key)} onChange={e => patch(key, e.target.value)}
                    placeholder={key.endsWith("2") ? "選填" : ""} />
              }
            </FormField>
          ))}

          {/* E. 訂購條件 */}
          <FormSectionDivider badge="E" label="訂購條件" />

          <FormField label="最低訂購量（MOQ）">
            {readOnly
              ? <FormFieldVal mono>{fv("moq") || "—"}</FormFieldVal>
              : <Field value={fv("moq")} onChange={e => patch("moq", e.target.value)} />
            }
          </FormField>

          <FormField label="最低訂購金額（MOA）">
            {readOnly
              ? <FormFieldVal mono>{fv("moa") ? `NT$${Number(fv("moa")).toLocaleString("zh-TW")}` : "—"}</FormFieldVal>
              : <NumInput value={fv("moa")} onChange={e => patch("moa", e.target.value)} unit="NT$" placeholder="0" />
            }
          </FormField>

          <FormField label="稅率">
            {readOnly
              ? <FormFieldVal mono>{fv("taxRate") !== "" && fv("taxRate") != null ? `${fv("taxRate")}%` : "—"}</FormFieldVal>
              : <NumInput value={fv("taxRate")} onChange={e => patch("taxRate", e.target.value)} unit="%" placeholder="0" />
            }
          </FormField>

          <FormField label="商品可退貨">
            {readOnly
              ? <FormFieldVal>{vendor.returnable === true ? "是" : vendor.returnable === false ? "否" : "—"}</FormFieldVal>
              : <RadioGroup options={[["是", true], ["否", false]]} value={vendor.returnable} onChange={v => patch("returnable", v)} />
            }
          </FormField>

          <FormField label="可退換">
            {readOnly
              ? <FormFieldVal>{vendor.exchangeable === true ? "是" : vendor.exchangeable === false ? "否" : "—"}</FormFieldVal>
              : <RadioGroup options={[["是", true], ["否", false]]} value={vendor.exchangeable} onChange={v => patch("exchangeable", v)} />
            }
          </FormField>

          <FormField label="瑕疵品處理">
            {readOnly
              ? <FormFieldVal>{fv("defectiveHandling") || "—"}</FormFieldVal>
              : <RadioGroup options={[["退貨", "退貨"], ["換貨", "換貨"]]} value={vendor.defectiveHandling} onChange={v => patch("defectiveHandling", v)} />
            }
          </FormField>

          {/* F. 財務帳務 */}
          <FormSectionDivider badge="F" label="財務帳務" />

          <FormField label="月底前開發票">
            {readOnly
              ? <FormFieldVal>{vendor.invoiceBeforeMonthEnd === true ? "是" : vendor.invoiceBeforeMonthEnd === false ? "否" : "—"}</FormFieldVal>
              : <RadioGroup options={[["是", true], ["否", false]]} value={vendor.invoiceBeforeMonthEnd} onChange={v => patch("invoiceBeforeMonthEnd", v)} />
            }
          </FormField>

          <FormField label="對帳負責單位">
            {readOnly
              ? <FormFieldVal>{fv("reconUnit") || "—"}</FormFieldVal>
              : <Field value={fv("reconUnit")} onChange={e => patch("reconUnit", e.target.value)} />
            }
          </FormField>

          <FormField label="帳期">
            {readOnly
              ? <FormFieldVal>{fv("paymentTerms") || "—"}</FormFieldVal>
              : <Field value={fv("paymentTerms")} onChange={e => patch("paymentTerms", e.target.value)}
                  placeholder="例：每月26號～隔月25號" />
            }
          </FormField>

          <FormField label="確認信寄送 Email">
            {readOnly
              ? <FormFieldVal>{fv("confirmEmailTo") || "—"}</FormFieldVal>
              : <Field value={fv("confirmEmailTo")} onChange={e => patch("confirmEmailTo", e.target.value)}
                  placeholder="多筆以分號分隔" />
            }
          </FormField>

          <FormField label="會計窗口 Email">
            {readOnly
              ? <FormFieldVal>{fv("accountingEmail") || "—"}</FormFieldVal>
              : <Field value={fv("accountingEmail")} onChange={e => patch("accountingEmail", e.target.value)}
                  placeholder="多筆以分號分隔" />
            }
          </FormField>

          <FormField label="會計窗口電話">
            {readOnly
              ? <FormFieldVal>{fv("accountingTel") || "—"}</FormFieldVal>
              : <Field value={fv("accountingTel")} onChange={e => patch("accountingTel", e.target.value)}
                  placeholder="選填" />
            }
          </FormField>

        </div>
      </SectionCard>

      {/* ── Card 2：廠商配送資料 ──────────────────────────────────── */}
      <div className="card">
        <SkuToolbar>
          <span style={{ color: "var(--fg-3)" }}>廠商配送資料</span>
          <span style={{ color: "var(--fg-2)", fontSize: "var(--fs-13)", whiteSpace: "nowrap" }}>
            　共 <b style={{ color: "var(--fg-1)" }}>{deliveries.length}</b> 筆
          </span>
          {!readOnly && (
            <Button variant="default" size="sm" icon="plus" style={{ marginLeft: "auto" }} onClick={addDelivRow}>
              新增配送規則
            </Button>
          )}
        </SkuToolbar>

        {deliveries.length === 0
          ? (
            <EmptyState icon="truck" title="尚無配送規則" desc="新增第一筆以設定此廠商的配送條件。">
              {!readOnly && <Button variant="primary" icon="plus" onClick={addDelivRow}>新增配送規則</Button>}
            </EmptyState>
          )
          : (
            <>
              <div className="tbl-wrap">
                <table className="tbl" style={{ tableLayout: "auto" }}>
                  <thead>
                    <TableGroupHeader cols={VD_COLS} groupLabels={VD_GROUP_LABELS}
                      actionCol={!readOnly ? { w: 44, label: "操作" } : null} />
                    <tr>
                      {VD_COLS.map(col => (
                        <th key={col.key} style={{ width: col.w, minWidth: col.w, whiteSpace: "nowrap" }}>
                          {col.label}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {deliveries.map(row => (
                      <tr key={row.uid}>
                        {VD_COLS.map(col => (
                          <td key={col.key} style={{ verticalAlign: "middle" }}>
                            {(readOnly || col.field.formula)
                              ? <CellDisplay field={col.field} value={row[col.key]} row={row} />
                              : <CellEditor alwaysOn field={col.field} value={row[col.key]} row={row}
                                  onCommit={val => patchDeliv(row.uid, col.key, val)} />}
                          </td>
                        ))}
                        {!readOnly && (
                          <td style={{ textAlign: "center", verticalAlign: "middle" }}>
                            <DeleteRowBtn onClick={() => deleteDeliv(row.uid)} />
                          </td>
                        )}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {!readOnly && (
                <button className="tbl-add-row" onClick={addDelivRow}>
                  <Icon name="plus" size={16} /> 新增配送規則
                </button>
              )}
            </>
          )
        }
      </div>
    </>
  );
};

Object.assign(window, { VendorDetail });
