/* global React, Icon, Button, Field, Check, SlideDrawer, ApprovalStatusBanner,
   FormField, FormFieldVal, FormSectionDivider, PortalSelect, useToast,
   PRODUCT_MASTER, DISCOUNT_TYPE_OPTIONS, isFriday, isThursday */
// EO 單筆品項編輯 Drawer — 從 EO L1 列表「編輯」按鈕觸發

const { useState } = React;

// ── 計算輔助（與 eo-detail / eo-create 邏輯一致，加 _edr 前綴避免命名衝突）──
const _edrCalcFinal  = (r) => r.u1PromoPrice || r.promoPrice || null;
const _edrRecalc = (r) => {
  const fp   = +(_edrCalcFinal(r) || 0);
  const cost = +(r.cost || 0);
  const sugg = +(r.suggestPrice || 0);
  const list = +(r.listPrice || 0);
  const bogo = r.discountType === "BOGO" || r.discountType === "Volume Discount";
  const bq   = +(r.buyQty || 0);
  return {
    ...r,
    finalPrice:  fp || null,
    marginPct:   fp ? +((fp - cost) / fp).toFixed(4) : null,
    discountPct: fp && sugg ? +(1 - fp / sugg).toFixed(4) : null,
    promoCheck:  fp && list ? (fp < list  ? "PASS" : "FAIL") : null,
    promoVsList: fp && sugg ? (fp < sugg  ? "PASS" : "FAIL") : null,
    promoDepth:  fp && list ? +((list - fp) / list).toFixed(4) : null,
    unitPrice:   bogo && fp && bq ? +(fp / bq).toFixed(2) : null,
    setPrice:    bogo && fp && bq ? +(fp * bq).toFixed(2) : null,
    buyQty:      bogo ? r.buyQty      : null,
    discountQty: bogo ? r.discountQty : null,
  };
};

const _edrAutoFill = (barcode, base = {}) => {
  const m = PRODUCT_MASTER.find(p => p.barcode === barcode);
  if (!m) return null;
  return _edrRecalc({
    ...base, barcode,
    name: m.name, mainCat: m.mainCat ?? "", subCat: m.subCat ?? "",
    cost: m.cost ?? null, listPrice: m.listPrice ?? null,
    suggestPrice: m.suggestPrice ?? null, vat: m.taxRate ?? "",
  });
};

// ── 格式化輔助 ──────────────────────────────────────────────────────────────
const _fmtNT  = (v) => v != null ? `NT$${(+v).toLocaleString("zh-TW", { minimumFractionDigits: 0, maximumFractionDigits: 2 })}` : null;
const _fmtPct = (v) => v != null ? `${(v * 100).toFixed(1)}%` : null;


// ── 2/3 欄 grid 容器 (CSS 在 ui-kit.css .drawer-grid，2026-06-02 從 inline style 提升) ─────
const DrwGrid = ({ cols = 2, children }) => (
  <div className={"drawer-grid" + (cols === 3 ? " drawer-grid--3col" : "")}>
    {children}
  </div>
);

// ── Formula / status 顯示值（唯讀，帶顏色語意）───────────────────────────────
const ChkVal = ({ v, kind }) => {
  if (v == null) return <FormFieldVal><span style={{ color: "var(--fg-4)" }}>—</span></FormFieldVal>;
  const isWarn = kind === "margin" && +v < 0.20;
  const isFail = (kind === "check") && v === "FAIL";
  const style = isWarn || isFail ? { color: "var(--danger, #DC2626)", fontWeight: 600 } : {};
  const txt = kind === "pct" || kind === "margin" ? _fmtPct(v) : String(v);
  return <FormFieldVal mono={kind !== "check"}><span style={style}>{txt}</span></FormFieldVal>;
};

// ── EoRowEditDrawer ──────────────────────────────────────────────────────────
const EoRowEditDrawer = ({ item: itemProp, readOnly, onClose, onSave }) => {
  const { push: toast } = useToast();
  const [item, setItem] = useState(() => _edrRecalc({ ...itemProp }));
  const [changed, setChanged] = useState(new Set());

  const patch = (updates) => {
    setItem(prev => _edrRecalc({ ...prev, ...updates }));
    setChanged(prev => {
      const next = new Set(prev);
      Object.keys(updates).forEach(k => next.add(k));
      return next;
    });
  };

  const handleBarcodeBlur = (val) => {
    if (val === item.barcode) return;
    const filled = _edrAutoFill(val, item);
    if (filled) {
      setItem(filled);
      setChanged(prev => {
        const next = new Set(prev);
        ["barcode","name","mainCat","subCat","cost","listPrice","suggestPrice","vat"].forEach(k => next.add(k));
        return next;
      });
    } else {
      patch({ barcode: val, name: "", mainCat: "", subCat: "", cost: null, listPrice: null, suggestPrice: null, vat: "" });
    }
  };

  const isRejected = item.status === "eoRejected";

  const handleSave = (close) => {
    if (isRejected) {
      // 重新送出：依毛利條件（< 20%）重新判斷是否送審；清除退回原因。
      // ⚠️ 「毛利率 < 20%」為 prototype 假條件，正式系統依審核流程設定模組判斷。
      const requiresReview = item.marginPct != null && item.marginPct < 0.20;
      const saved = { ...item, status: requiresReview ? "eoUnderReview" : "eoNoReview", rejectReason: "" };
      onSave(saved);
      close();
      toast(requiresReview
        ? { kind: "warning", msg: `${saved.name || saved.barcode} 已重新送出，待審核` }
        : { kind: "success", msg: `${saved.name || saved.barcode} 已重新送出並生效` });
      return;
    }
    onSave(item);
    close();
    toast({ kind: "success", msg: `${item.name || item.barcode} 已更新` });
  };

  const isDirty   = changed.size > 0;
  const isBogoType = item.discountType === "BOGO" || item.discountType === "Volume Discount";

  // menuPromoStart / End validation hints
  const menuStartErr = item.menuPromoStart && !isFriday(item.menuPromoStart) ? "需為週五" : null;
  const menuEndErr   = item.menuPromoEnd   && !isThursday(item.menuPromoEnd) ? "需為週四" : null;

  const barcodeChip = item.barcode
    ? <span style={{ font: "500 12px var(--font-mono)", background: "var(--gray-100)", padding: "2px 8px", borderRadius: 4, color: "var(--fg-1)", flexShrink: 0 }}>{item.barcode}</span>
    : null;

  return (
    <SlideDrawer
      title={item.name || item.barcode || (readOnly ? "檢視品項" : "編輯品項")}
      meta={barcodeChip}
      isDirty={readOnly ? false : isDirty}
      dirtyCount={changed.size}
      dirtyMsg={`此品項有 ${changed.size} 個欄位已修改，關閉後變更將會遺失。`}
      onClose={onClose}
      foot={(tryClose) => (
        readOnly
          ? <Button variant="secondary" onClick={tryClose}>關閉</Button>
          : <>
              <Button variant="text" onClick={tryClose}>取消</Button>
              <Button variant="primary" onClick={() => handleSave(onClose)}>{isRejected ? "重新送出" : "儲存"}</Button>
            </>
      )}
    >

      {isRejected && (
        <ApprovalStatusBanner variant="rejected"
          msg={`此品項已被退回：${item.rejectReason || "（未填寫退回原因）"}`} />
      )}

      {/* ── A 申請資訊 ── */}
      <FormSectionDivider badge="A" label="申請資訊" first />
      <DrwGrid>
        <FormField label="申請人" locked>
          <FormFieldVal>{item.applicant || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
        <FormField label="更新時間" locked>
          <FormFieldVal mono>{item.updatedAt || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
      </DrwGrid>

      {/* ── B 商品基本 ── */}
      <FormSectionDivider badge="B" label="商品基本" />
      <DrwGrid>
        <FormField label="品號" required={!readOnly} locked={readOnly}>
          {readOnly
            ? <FormFieldVal mono>{item.barcode || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
            : <input className="field mono" defaultValue={item.barcode} onBlur={e => handleBarcodeBlur(e.target.value.trim())} />
          }
        </FormField>
        <FormField label="品名" locked style={{ gridColumn: "span 2" }}>
          <FormFieldVal>{item.name || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
        <FormField label="主類別" locked>
          <FormFieldVal>{item.mainCat || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
        <FormField label="次類別" locked>
          <FormFieldVal>{item.subCat || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
      </DrwGrid>

      {/* ── C 進價 ── */}
      <FormSectionDivider badge="C" label="進價" />
      <DrwGrid>
        <FormField label="進價（未稅）" locked>
          <FormFieldVal mono>{_fmtNT(item.cost) || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
        <FormField label="新進價" locked={readOnly}>
          {readOnly
            ? <FormFieldVal mono>{_fmtNT(item.newCost) || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
            : <input className="field mono" type="number" value={item.newCost ?? ""} placeholder="NT$" onChange={e => patch({ newCost: e.target.value ? +e.target.value : null })} />
          }
        </FormField>
        <FormField label="促進開始" locked={readOnly}>
          {readOnly
            ? <FormFieldVal mono>{item.promoStart || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
            : <input className="field mono" type="date" value={item.promoStart || ""} onChange={e => patch({ promoStart: e.target.value })} />
          }
        </FormField>
        <FormField label="促進結束" locked={readOnly}>
          {readOnly
            ? <FormFieldVal mono>{item.promoEnd || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
            : <input className="field mono" type="date" value={item.promoEnd || ""} onChange={e => patch({ promoEnd: e.target.value })} />
          }
        </FormField>
      </DrwGrid>

      {/* ── D 售價 ── */}
      <FormSectionDivider badge="D" label="售價" />
      <DrwGrid>
        <FormField label="牌價" locked>
          <FormFieldVal mono>{_fmtNT(item.listPrice) || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
        <FormField label="建議售價" locked>
          <FormFieldVal mono>{_fmtNT(item.suggestPrice) || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
        <FormField label="促銷售價" required={!readOnly} locked={readOnly}>
          {readOnly
            ? <FormFieldVal mono>{_fmtNT(item.promoPrice) || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
            : <input className="field mono" type="number" value={item.promoPrice ?? ""} placeholder="NT$" onChange={e => patch({ promoPrice: e.target.value ? +e.target.value : null })} />
          }
        </FormField>
        <FormField label="U1 Promo Price" locked={readOnly}>
          {readOnly
            ? <FormFieldVal mono>{_fmtNT(item.u1PromoPrice) || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
            : <input className="field mono" type="number" value={item.u1PromoPrice ?? ""} placeholder="NT$" onChange={e => patch({ u1PromoPrice: e.target.value ? +e.target.value : null })} />
          }
        </FormField>
        <FormField label="最終新售價" locked>
          <FormFieldVal mono>{_fmtNT(item.finalPrice) || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
        <FormField label="折扣種類" required={!readOnly} locked={readOnly}>
          {readOnly
            ? <FormFieldVal>{DISCOUNT_TYPE_OPTIONS.find(o => o.value === item.discountType)?.label || item.discountType || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
            : <PortalSelect value={item.discountType} options={DISCOUNT_TYPE_OPTIONS} onChange={v => patch({ discountType: v })} triggerClassName="field-trigger" placeholder="選擇…" />
          }
        </FormField>
        <FormField label="購買數量" locked={!isBogoType || readOnly}>
          {!readOnly && isBogoType
            ? <input className="field mono" type="number" value={item.buyQty ?? ""} placeholder="件數" onChange={e => patch({ buyQty: e.target.value ? +e.target.value : null })} />
            : <FormFieldVal mono>{item.buyQty ?? <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
          }
        </FormField>
        <FormField label="折扣數量" locked={!isBogoType || readOnly}>
          {!readOnly && isBogoType
            ? <input className="field mono" type="number" value={item.discountQty ?? ""} placeholder="件數" onChange={e => patch({ discountQty: e.target.value ? +e.target.value : null })} />
            : <FormFieldVal mono>{item.discountQty ?? <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
          }
        </FormField>
        <FormField label="折算單件價" locked>
          <FormFieldVal mono>{_fmtNT(item.unitPrice) || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
        <FormField label="商品一組價" locked>
          <FormFieldVal mono>{_fmtNT(item.setPrice) || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
        <FormField label="是否做 Eats Offer" locked>
          <FormFieldVal>YES</FormFieldVal>
        </FormField>
      </DrwGrid>

      {/* ── E 促銷期間 ── */}
      <FormSectionDivider badge="E" label="促銷期間" />
      <DrwGrid>
        <FormField label="菜單促銷開始" hint={readOnly ? null : "需為週五"} error={readOnly ? null : menuStartErr} locked={readOnly}>
          {readOnly
            ? <FormFieldVal mono>{item.menuPromoStart || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
            : <input className={"field mono" + (menuStartErr ? " field--error" : "")} type="date" value={item.menuPromoStart || ""} onChange={e => patch({ menuPromoStart: e.target.value })} />
          }
        </FormField>
        <FormField label="菜單促銷結束" hint={readOnly ? null : "需為週四"} error={readOnly ? null : menuEndErr} locked={readOnly}>
          {readOnly
            ? <FormFieldVal mono>{item.menuPromoEnd || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
            : <input className={"field mono" + (menuEndErr ? " field--error" : "")} type="date" value={item.menuPromoEnd || ""} onChange={e => patch({ menuPromoEnd: e.target.value })} />
          }
        </FormField>
        <FormField label="限購上限" locked={readOnly}>
          {readOnly
            ? <FormFieldVal mono>{item.purchaseLimit ?? <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
            : <input className="field mono" type="number" value={item.purchaseLimit ?? ""} placeholder="件數" onChange={e => patch({ purchaseLimit: e.target.value ? +e.target.value : null })} />
          }
        </FormField>
      </DrwGrid>

      {/* ── F 驗算 ── */}
      <FormSectionDivider badge="F" label="驗算" />
      <DrwGrid cols={3}>
        <FormField label="毛利率 M%" locked>
          <ChkVal v={item.marginPct} kind="margin" />
        </FormField>
        <FormField label="折扣 %off" locked>
          <ChkVal v={item.discountPct} kind="pct" />
        </FormField>
        <FormField label="真促銷幅度" locked>
          <ChkVal v={item.promoDepth} kind="pct" />
        </FormField>
        <FormField label="真促銷價檢查" locked>
          <ChkVal v={item.promoCheck} kind="check" />
        </FormField>
        <FormField label="促銷<>牌價" locked>
          <ChkVal v={item.promoVsList} kind="check" />
        </FormField>
        <FormField label="疊價幅度" locked>
          <ChkVal v={item.stackDepth} kind="pct" />
        </FormField>
        <FormField label="牌價自動調整" locked>
          <ChkVal v={item.autoListAdj} kind="check" />
        </FormField>
        <FormField label="自動牌價白名單" style={{ gridColumn: "span 2" }} locked={readOnly}>
          {readOnly
            ? <FormFieldVal>{item.autoListWhitelist ? "是" : "否"}</FormFieldVal>
            : <div style={{ display: "inline-flex", alignItems: "center", gap: 6, height: 28 }}>
                <Check checked={!!item.autoListWhitelist} onChange={val => patch({ autoListWhitelist: val })} />
                <span style={{ font: "400 13px var(--font-sans)", color: "var(--fg-2)" }}>{item.autoListWhitelist ? "是" : "否"}</span>
              </div>
          }
        </FormField>
      </DrwGrid>

      {/* ── G 參考資料 ── */}
      <FormSectionDivider badge="G" label="參考資料" />
      <DrwGrid>
        <FormField label="市調售價" locked>
          <FormFieldVal mono>{_fmtNT(item.marketPrice) || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
        <FormField label="POC(copy)" locked>
          <FormFieldVal>{item.poc || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
      </DrwGrid>

      {/* ── H VAT ── */}
      <FormSectionDivider badge="H" label="VAT" />
      <DrwGrid>
        <FormField label="VAT" locked>
          <FormFieldVal>{item.vat || <span style={{ color: "var(--fg-4)" }}>—</span>}</FormFieldVal>
        </FormField>
      </DrwGrid>

      {/* ── I ERP ── */}
      <FormSectionDivider badge="I" label="ERP" />
      <DrwGrid>
        <FormField label="進價已建檔" locked>
          <FormFieldVal>
            {item.costInErp
              ? <span style={{ color: "var(--fg-1)", fontWeight: 500 }}>✓</span>
              : <span style={{ color: "var(--fg-4)" }}>—</span>}
          </FormFieldVal>
        </FormField>
        <FormField label="Time Check" locked>
          <FormFieldVal>
            {item.timeCheck
              ? <span style={{ color: "var(--fg-1)", fontWeight: 500 }}>✓</span>
              : <span style={{ color: "var(--fg-4)" }}>—</span>}
          </FormFieldVal>
        </FormField>
      </DrwGrid>

    </SlideDrawer>
  );
};

Object.assign(window, { EoRowEditDrawer });
