/* global React, Button, PageHead, Pager, FilterBar, RowActions, EmptyState, ImportBanner, runImportProgress, useToast, PAGE_SIZES, useSortableTable */

const { useState, useMemo } = React;

const IncaFileList = ({ files, config, onGenerate, onDelete }) => {
  const [q, setQ] = useState("");
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);
  const [genPhase, setGenPhase] = useState(null);
  const [genDone, setGenDone] = useState(0);
  const toast = useToast();
  const { SortHead, applySortTo } = useSortableTable("createdAt", "desc");

  const filtered = useMemo(() => {
    const lq = q.trim().toLowerCase();
    return applySortTo(files.filter(f => !lq || f.name.toLowerCase().includes(lq)));
  }, [files, q, applySortTo]);

  const paged = filtered.slice((page - 1) * pageSize, page * pageSize);

  const handleGenerate = () => {
    if (genPhase === "parsing") return;
    onGenerate();
    setGenDone(0);
    setGenPhase("parsing");
    runImportProgress(config.fileCount, setGenDone, () => {
      setGenPhase("ok");
      setTimeout(() => setGenPhase(null), 1500);
    });
  };

  return (
    <>
      <PageHead
        section={config.section}
        title={config.title}
        subtitle={config.subtitle}
        actions={
          <Button variant="primary" onClick={handleGenerate} disabled={genPhase === "parsing"}>
            {genPhase === "parsing" ? "產出中…" : "+ 新增"}
          </Button>
        }
      />

      <ImportBanner
        phase={genPhase}
        parsingTitle={config.progressTitle}
        total={config.fileCount}
        done={genDone}
        unit="個檔案"
        okTitle={config.okTitle}
        okDesc=""
      />

      <FilterBar filters={[
        { type: "search", placeholder: "搜尋版本名稱…", value: q, onChange: v => { setQ(v); setPage(1); } },
      ]} />

      <div className="card">
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th style={{ width: 160 }}><SortHead colKey="createdAt" label="產出時間" /></th>
                <th><SortHead colKey="name" label="版本名稱" /></th>
                <th style={{ width: 160 }} className="center">功能</th>
              </tr>
            </thead>
            <tbody>
              {paged.length === 0 ? (
                <tr><td colSpan={3}><EmptyState icon="file" title={q ? `沒有符合「${q}」的版本` : config.emptyTitle} style={{ padding: "40px 0" }} /></td></tr>
              ) : paged.map(f => (
                <tr key={f.id}>
                  <td className="mono" style={{ color: "var(--fg-2)" }}>{f.createdAt}</td>
                  <td style={{ fontWeight: "var(--fw-semibold)" }}>{f.name}</td>
                  <td className="center">
                    <RowActions actions={[
                      { label: "匯出", onClick: () => toast.push({ msg: `${f.name} 已匯出` }) },
                      { label: "刪除", danger: true, onClick: () => onDelete(f) },
                    ]} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <Pager total={filtered.length} page={page} pageSize={pageSize}
          onPageChange={setPage} onSizeChange={s => { setPageSize(s); setPage(1); }} />
      </div>
    </>
  );
};

const INCA_LIST_CONFIG = {
  "m-cat": {
    section: "菜單",
    title: "Catalog file 商品資訊更新檔案 INCA",
    subtitle: "依商品主檔產出 Catalog File 供上傳至 Uber Eats 系統。",
    fileCount: 1,
    progressTitle: "Catalog File 產出中…",
    okTitle: "已建立 Catalog File",
    emptyTitle: "尚無 Catalog File",
    nameSuffix: "Catalog_File",
  },
  "m-promo": {
    section: "菜單",
    title: "Promotion file 商家折扣檔案 INCA",
    subtitle: "依促銷活動產出 Promotion File 供上傳至 Uber Eats 系統。",
    fileCount: 1,
    progressTitle: "Promotion File 產出中…",
    okTitle: "已建立 Promotion File",
    emptyTitle: "尚無 Promotion File",
    nameSuffix: "Promotion_File",
  },
};

Object.assign(window, { IncaFileList, INCA_LIST_CONFIG });
