/* global React, Icon, Button, Dialog, ImportBanner, runImportProgress, IMG_SLOTS, IMG_SKUS */
// 圖片更新檔匯入 — 6 步驟流程（#11960）

const { useState, useRef, useMemo } = React;

const IMPORT_STEPS = [
  "下載匯入格式",
  "選擇檔案",
  "解析檔案",
  "比對品號",
  "確認覆蓋",
  "匯入完成",
];

const buildMockRows = () => {
  const samples = IMG_SKUS.slice(0, 5);
  return samples.map(sku => ({
    barcode: sku.barcode,
    name: sku.name,
    matched: true,
    updates: IMG_SLOTS.reduce((acc, slot) => {
      if (sku[slot.key]) acc[slot.key] = `https://cdn.example.com/${sku.barcode}/${slot.key}.jpg`;
      return acc;
    }, {}),
  })).concat([{
    barcode: "9999999999999",
    name: "—",
    matched: false,
    updates: {},
  }]);
};

const ImageImportDialog = ({ open, onClose, onApply, currentUser }) => {
  const [step, setStep] = useState(1);
  const [parsePhase, setParsePhase] = useState(null);
  const [parseTotal, setParseTotal] = useState(0);
  const [parseDone, setParseDone] = useState(0);
  const [previewRows, setPreviewRows] = useState([]);
  const fileInputRef = useRef(null);

  const matchedRows = useMemo(
    () => previewRows.filter(r => r.matched),
    [previewRows]
  );
  const unmatchedCount = previewRows.length - matchedRows.length;

  const reset = () => {
    setStep(1);
    setParsePhase(null);
    setParseTotal(0);
    setParseDone(0);
    setPreviewRows([]);
  };

  const handleClose = () => {
    reset();
    onClose();
  };

  const handleDownloadTemplate = () => {
    setStep(2);
  };

  const handleFileSelect = () => {
    if (!fileInputRef.current) return;
    fileInputRef.current.click();
  };

  const handleFileChange = (e) => {
    if (!e.target.files || !e.target.files[0]) return;
    const rows = buildMockRows();
    setStep(3);
    setParsePhase("parsing");
    setParseTotal(rows.length);
    setParseDone(0);
    runImportProgress(rows.length, setParseDone, () => {
      setPreviewRows(rows);
      setParsePhase("ok");
      setStep(4);
      setTimeout(() => setParsePhase(null), 800);
    });
    e.target.value = "";
  };

  const handleGoConfirm = () => {
    if (!matchedRows.length) return;
    setStep(5);
  };

  const handleConfirmApply = () => {
    const now = new Date().toLocaleString("zh-TW", { hour12: false }).replace(",", "").slice(0, 16);
    matchedRows.forEach(row => {
      const sku = IMG_SKUS.find(s => s.barcode === row.barcode);
      if (!sku) return;
      Object.entries(row.updates).forEach(([key, val]) => { sku[key] = val; });
      sku.lastUpdated = now;
      sku.updatedBy = currentUser;
    });
    onApply(matchedRows.length);
    setStep(6);
  };

  const stepLabel = IMPORT_STEPS[step - 1];

  return (
    <Dialog
      open={open}
      title={`圖片更新檔匯入 — 步驟 ${step}/6：${stepLabel}`}
      onClose={handleClose}
      dialogClassName="dialog--img-import"
      footer={
        <>
          {step === 1 && (
            <>
              <Button variant="secondary" onClick={handleClose}>取消</Button>
              <Button variant="default" icon="download" onClick={handleDownloadTemplate}>下載匯入格式</Button>
            </>
          )}
          {step === 2 && (
            <>
              <Button variant="secondary" onClick={() => setStep(1)}>上一步</Button>
              <Button variant="primary" icon="upload" onClick={handleFileSelect}>選擇檔案</Button>
            </>
          )}
          {step === 4 && (
            <>
              <Button variant="secondary" onClick={handleClose}>取消</Button>
              <Button variant="primary" disabled={!matchedRows.length} onClick={handleGoConfirm}>
                下一步（{matchedRows.length} 筆可更新）
              </Button>
            </>
          )}
          {step === 5 && (
            <>
              <Button variant="secondary" onClick={() => setStep(4)}>上一步</Button>
              <Button variant="primary" icon="check" onClick={handleConfirmApply}>確認覆蓋更新</Button>
            </>
          )}
          {step === 6 && (
            <Button variant="primary" onClick={handleClose}>關閉</Button>
          )}
        </>
      }
    >
      <input
        ref={fileInputRef}
        type="file"
        accept=".xlsx,.xls,.csv"
        style={{ display: "none" }}
        onChange={handleFileChange}
      />

      {step === 1 && (
        <div className="img-import-step">
          <p style={{ margin: "0 0 12px", color: "var(--fg-2)", fontSize: "var(--fs-13)" }}>
            請先下載匯入格式，填寫各品項的圖片 URL 後上傳。系統會依「品號」比對列表資料，覆蓋更新既有圖片連結。
          </p>
          <ul className="img-import-step__list">
            <li>欄位包含：品號 + 7 個圖片欄位（商品主圖、活動圖檔…）</li>
            <li>品號需與列表完全一致，否則該列略過</li>
            <li>空白欄位不會覆蓋原值</li>
          </ul>
        </div>
      )}

      {step === 2 && (
        <div className="img-import-step">
          <p style={{ margin: "0 0 12px", color: "var(--fg-2)", fontSize: "var(--fs-13)" }}>
            匯入格式已下載。請填寫完成後，點「選擇檔案」上傳 Excel。
          </p>
          <div className="img-import-step__drop" onClick={handleFileSelect}>
            <Icon name="upload" size={24} />
            <span>點擊選擇檔案，或拖曳至此</span>
            <small>支援 .xlsx / .xls / .csv</small>
          </div>
        </div>
      )}

      {step === 3 && parsePhase && (
        <ImportBanner
          phase={parsePhase}
          parsingTitle="解析匯入檔案中…"
          total={parseTotal}
          done={parseDone}
          okTitle="解析完成"
        />
      )}

      {step === 4 && (
        <div className="img-import-step">
          <p style={{ margin: "0 0 8px", fontSize: "var(--fs-13)", color: "var(--fg-2)" }}>
            比對完成：可更新 <b style={{ color: "var(--fg-1)" }}>{matchedRows.length}</b> 筆
            {unmatchedCount > 0 && <>，略過 <b style={{ color: "var(--danger)" }}>{unmatchedCount}</b> 筆（查無品號）</>}
          </p>
          <div className="tbl-wrap" style={{ maxHeight: 280, overflow: "auto" }}>
            <table className="tbl">
              <thead>
                <tr>
                  <th>品號</th>
                  <th>品名</th>
                  <th>狀態</th>
                  <th>更新欄位數</th>
                </tr>
              </thead>
              <tbody>
                {previewRows.map(row => (
                  <tr key={row.barcode}>
                    <td className="mono">{row.barcode}</td>
                    <td>{row.name}</td>
                    <td>
                      {row.matched
                        ? <span style={{ color: "var(--success)" }}>比對成功</span>
                        : <span style={{ color: "var(--danger)" }}>查無品號</span>
                      }
                    </td>
                    <td>{row.matched ? Object.keys(row.updates).length : "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {step === 5 && (
        <div className="img-import-step">
          <p style={{ margin: 0, fontSize: "var(--fs-13)", color: "var(--fg-2)" }}>
            即將覆蓋更新 <b style={{ color: "var(--fg-1)" }}>{matchedRows.length}</b> 筆品項的圖片連結。此操作送出後立即生效，無法復原。
          </p>
        </div>
      )}

      {step === 6 && (
        <div className="img-import-step img-import-step--ok">
          <Icon name="check" size={32} />
          <p style={{ margin: "12px 0 0", fontSize: "var(--fs-14)", fontWeight: "var(--fw-medium)" }}>
            已成功匯入 {matchedRows.length} 筆品項的圖片更新
          </p>
        </div>
      )}
    </Dialog>
  );
};

Object.assign(window, { ImageImportDialog });
