/* global React, Icon, Button, Dialog, Tag, Field, PortalSelect, EmptyState, PRICE_HISTORY */
// 商品主檔 — 進價歷史紀錄 Dialog（#8682）

const { useState, useMemo } = React;

const PH_DLG_COLS = [
  { key: "#", label: "#", w: 48 },
  { key: "barcode", label: "品號", w: 140, mono: true },
  { key: "name", label: "品名", w: 200 },
  { key: "supplierShort", label: "廠商簡稱", w: 100 },
  { key: "costExTax", label: "未稅進價", w: 100, price: true },
  { key: "costIncTax", label: "含稅進價", w: 100, price: true },
  { key: "effectiveDate", label: "生效日", w: 100, mono: true },
  { key: "expiryDate", label: "失效日", w: 100, mono: true },
  { key: "effectiveStatus", label: "目前正在生效嗎？", w: 120, center: true },
];

const phDlgFmtPrice = (val, currency) => {
  if (val === "" || val == null) return null;
  const n = Number(val);
  if (currency === "USD") return `USD ${n.toFixed(2)}`;
  return `NT$${n.toLocaleString("zh-TW", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};

const phDlgRenderCell = (item, c, idx) => {
  if (c.key === "#") return <span style={{ color: "var(--fg-3)", fontSize: "var(--fs-12)" }}>{idx + 1}</span>;
  const v = item[c.key];
  if (v === "" || v == null) return <span className="cell-empty">—</span>;
  if (c.key === "effectiveStatus") return <Tag status={v} />;
  if (c.price) return <span className="mono" style={{ fontSize: "var(--fs-12)" }}>{phDlgFmtPrice(v, item.currency)}</span>;
  if (c.mono) return <span className="mono" style={{ fontSize: "var(--fs-12)" }}>{v}</span>;
  return v;
};

const EFF_FILTER_OPTS = [
  { value: "", label: "請選擇" },
  { value: "active", label: "是" },
  { value: "expired", label: "否" },
];

const PriceHistoryDialog = ({ barcode, itemName, onClose }) => {
  const [keyword, setKeyword] = useState(barcode || "");
  const [effFilter, setEffFilter] = useState("");
  const [applied, setApplied] = useState({ keyword: barcode || "", effFilter: "" });

  const rows = useMemo(() => {
    let list = PRICE_HISTORY.filter(h => h.barcode === barcode);
    const kw = applied.keyword.trim();
    if (kw) {
      list = list.filter(h =>
        (h.barcode || "").includes(kw) ||
        (h.name || "").includes(kw)
      );
    }
    if (applied.effFilter) {
      list = list.filter(h => h.effectiveStatus === applied.effFilter);
    }
    return [...list].sort((a, b) => (b.effectiveDate || "").localeCompare(a.effectiveDate || ""));
  }, [barcode, applied]);

  const handleSearch = () => setApplied({ keyword, effFilter });
  const handleReset = () => {
    setKeyword(barcode || "");
    setEffFilter("");
    setApplied({ keyword: barcode || "", effFilter: "" });
  };

  return (
    <Dialog
      open
      title="進價歷史紀錄"
      onClose={onClose}
      footer={<Button variant="default" onClick={onClose}>關閉</Button>}
    >
      <div style={{ display: "flex", flexDirection: "column", gap: 12, minWidth: 480 }}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "flex-end" }}>
          <div style={{ flex: "1 1 200px" }}>
            <div style={{ fontSize: "var(--fs-12)", color: "var(--fg-2)", marginBottom: 4 }}>關鍵字</div>
            <Field value={keyword} onChange={setKeyword} placeholder="品號或品名…" />
          </div>
          <div style={{ flex: "0 0 160px" }}>
            <div style={{ fontSize: "var(--fs-12)", color: "var(--fg-2)", marginBottom: 4 }}>目前正在生效嗎？</div>
            <PortalSelect
              value={effFilter}
              options={EFF_FILTER_OPTS}
              onChange={setEffFilter}
              placeholder="請選擇"
              triggerClassName="field-trigger"
            />
          </div>
          <Button variant="default" onClick={handleSearch}>查詢</Button>
          <Button variant="text" onClick={handleReset}>重新查詢</Button>
        </div>

        {itemName && (
          <div style={{ fontSize: "var(--fs-13)", color: "var(--fg-2)" }}>
            品號 <span className="mono" style={{ color: "var(--fg-1)" }}>{barcode}</span>
            {itemName ? <> · {itemName}</> : null}
          </div>
        )}

        <div className="tbl-wrap" style={{ maxHeight: 360, overflow: "auto" }}>
          {rows.length === 0 ? (
            <EmptyState icon="inbox" title="查無進價歷史" desc="此品號尚無進價歷史紀錄。" />
          ) : (
            <table className="tbl" style={{ minWidth: PH_DLG_COLS.reduce((s, c) => s + c.w, 0) }}>
              <thead>
                <tr>
                  {PH_DLG_COLS.map(c => (
                    <th key={c.key} style={{ width: c.w, minWidth: c.w }}
                      className={[c.center ? "center" : "", c.mono ? "" : ""].filter(Boolean).join(" ")}>
                      {c.label}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {rows.map((row, idx) => (
                  <tr key={`${row.barcode}-${row.effectiveDate}-${idx}`}>
                    {PH_DLG_COLS.map(c => (
                      <td key={c.key} className={c.center ? "center" : ""}>
                        {phDlgRenderCell(row, c, idx)}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {rows.length > 0 && (
          <div style={{ fontSize: "var(--fs-12)", color: "var(--fg-2)" }}>
            共 <b style={{ color: "var(--fg-1)" }}>{rows.length}</b> 筆
          </div>
        )}
      </div>
    </Dialog>
  );
};

Object.assign(window, { PriceHistoryDialog });
