/* global React, Button, PageHead, RowActions, useToast, useSortableTable */

const { useMemo } = React;

const PARENT_COLS = [
  { key: "fileType", label: "類型", w: 80 },
  { key: "genMethod", label: "生成方式", w: 110 },
  { key: "genTime", label: "生成時間", w: 150, mono: true },
  { key: "updatedAt", label: "最新異動時間", w: 150, mono: true },
  { key: "name", label: "檔案名稱" },
  { key: "incaStartTime", label: "開始輸出至 INCA 時間", w: 170, mono: true },
  { key: "incaResult", label: "輸出至 INCA 結果", w: 140 },
];

const STORE_COLS = [
  { key: "fileType", label: "類型", w: 72 },
  { key: "genMethod", label: "生成方式", w: 100 },
  { key: "storeId", label: "店家", w: 64 },
  { key: "genTime", label: "生成時間", w: 140, mono: true },
  { key: "updatedAt", label: "最新異動時間", w: 140, mono: true },
  { key: "fileName", label: "檔案名稱", w: 240, mono: true },
  { key: "incaStartTime", label: "開始輸出至 INCA 時間", w: 160, mono: true },
  { key: "incaResult", label: "輸出至 INCA 結果", w: 130 },
  { key: "virtualSyncVersion", label: "虛擬 Sync File 生成版本", w: 160, mono: true },
  { key: "compareSyncVersion", label: "補比對 Sync File 舊版本", w: 170, mono: true },
];

const renderResult = (text) => {
  if (!text || text === "—") return "—";
  if (text.includes("，")) {
    return text.split("，").map((part, i) => (
      <span key={part}>
        {i > 0 ? "，" : ""}
        <span style={part.includes("失敗") ? { color: "var(--danger)" } : undefined}>{part}</span>
      </span>
    ));
  }
  if (text.includes("失敗")) {
    return <span style={{ color: "var(--danger)" }}>{text}</span>;
  }
  return text;
};

const DeltaFileDetail = ({ file, onBack }) => {
  const toast = useToast();
  const { SortHead, applySortTo } = useSortableTable("storeId", "asc");

  const storeRows = useMemo(
    () => applySortTo(file.stores || []),
    [file.stores, applySortTo],
  );

  const storeActions = (row) => {
    const actions = [
      { label: "匯出", onClick: () => toast.push({ msg: `${row.fileName} 已匯出` }) },
    ];
    if (row.incaResult && row.incaResult.includes("失敗")) {
      actions.push({
        label: "生成 APPEND 檔",
        onClick: () => toast.push({ kind: "success", msg: `${row.storeId} 已觸發生成 APPEND 檔` }),
      });
      actions.push({
        label: "上傳至 INCA 系統",
        onClick: () => toast.push({ kind: "success", msg: `${row.fileName} 已上傳至 INCA 系統` }),
      });
    }
    return actions;
  };

  const renderCell = (row, col) => {
    const val = row[col.key];
    if (col.key === "incaResult") return renderResult(val);
    if (col.key === "name") return <span style={{ fontWeight: "var(--fw-semibold)" }}>{val}</span>;
    return val;
  };

  return (
    <>
      <PageHead
        crumbs={[
          { label: "菜單" },
          { label: "Delta file 商家價格、庫存檔案 INCA", onClick: onBack },
          { label: file.name, current: true },
        ]}
        title={`${file.name} · 檢視`}
        subtitle="上方為批次母資料；下方為 W01–W13 各店個別檔案生成與上傳結果。"
        actions={
          <>
            <Button variant="default" onClick={onBack}>返回</Button>
            <Button variant="primary" onClick={() => toast.push({ msg: `${file.name} 已全部匯出（共 13 個檔案）` })}>
              全部匯出
            </Button>
          </>
        }
      />

      <div className="card" style={{ marginBottom: 16 }}>
        <div className="card__section-title" style={{ padding: "12px 16px 0", fontWeight: "var(--fw-semibold)" }}>
          批次資訊
        </div>
        <div className="tbl-wrap">
          <table className="tbl" style={{ minWidth: 1100 }}>
            <thead>
              <tr>
                {PARENT_COLS.map(col => (
                  <th key={col.key} style={col.w ? { width: col.w } : undefined}>{col.label}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              <tr>
                {PARENT_COLS.map(col => (
                  <td key={col.key} className={col.mono ? "mono" : undefined} style={{ color: col.mono ? "var(--fg-2)" : undefined }}>
                    {col.key === "incaResult" ? renderResult(file[col.key]) : renderCell(file, col)}
                  </td>
                ))}
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <div className="card">
        <div className="card__section-title" style={{ padding: "12px 16px 0", fontWeight: "var(--fw-semibold)" }}>
          所有店家（共 <b style={{ color: "var(--fg-1)" }}>{storeRows.length}</b> 筆）
        </div>
        <div className="tbl-wrap">
          <table className="tbl" style={{ minWidth: 1680 }}>
            <thead>
              <tr>
                {STORE_COLS.map(col => (
                  <th key={col.key} style={col.w ? { width: col.w, minWidth: col.w } : undefined}>
                    <SortHead colKey={col.key} label={col.label} />
                  </th>
                ))}
                <th style={{ width: 240 }} className="center">功能</th>
              </tr>
            </thead>
            <tbody>
              {storeRows.map(row => (
                <tr key={row.storeId}>
                  {STORE_COLS.map(col => (
                    <td
                      key={col.key}
                      className={col.mono ? "mono" : undefined}
                      style={{
                        fontSize: col.mono ? "var(--fs-12)" : undefined,
                        color: col.mono ? "var(--fg-2)" : undefined,
                      }}
                    >
                      {renderCell(row, col)}
                    </td>
                  ))}
                  <td className="center">
                    <RowActions actions={storeActions(row)} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
};

Object.assign(window, { DeltaFileDetail });
