/* global React, Button, PageHead, FilterBar, Pager, PAGE_SIZES, useSortableTable, Tag, UserChip, RowActions, useToast */

const { useState, useMemo } = React;

const PromoStubList = ({ pageId, config, sectionLabel, titleLabel }) => {
  const [q, setQ] = useState("");
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);
  const { SortHead, applySortTo } = useSortableTable("updatedAt", "desc");
  const { push: toast } = useToast();
  const rows = PROMO_STUB_SEEDS[pageId] || [];
  const isActivity = config.variant === "activity";

  const filtered = useMemo(() => {
    const lq = q.trim().toLowerCase();
    const base = !lq ? rows : rows.filter(r => {
      const hay = isActivity
        ? [r.name, r.applicant].join(" ")
        : [r.name, r.skuNo, r.promoType, r.slot].filter(Boolean).join(" ");
      return hay.toLowerCase().includes(lq);
    });
    return applySortTo(base, (row, key) => {
      if (key === "itemCount") return row.itemCount ?? 0;
      return row[key] ?? "";
    });
  }, [rows, q, applySortTo, isActivity]);

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

  const viewRow = () => toast({ kind: "success", msg: "原型僅展示列表，L2 待實作" });

  return (
    <>
      <PageHead
        section={sectionLabel}
        title={titleLabel}
        subtitle={config.subtitle}
        actions={<Button variant="primary" icon="plus" onClick={viewRow}>{config.addLabel}</Button>}
      />

      <FilterBar filters={[
        { type: "search", placeholder: config.searchPlaceholder, value: q, onChange: v => { setQ(v); setPage(1); } },
      ]} />

      <div className="card">
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              {isActivity ? (
                <tr>
                  <th style={{ width: 150 }}><SortHead colKey="updatedAt" label="更新時間" /></th>
                  <th style={{ width: 100 }}><SortHead colKey="applicant" label="申請人" /></th>
                  <th><SortHead colKey="name" label={config.nameCol} /></th>
                  <th style={{ width: 210 }}><SortHead colKey="campaignStart" label="活動期間" /></th>
                  <th style={{ width: 85 }} className="num"><SortHead colKey="itemCount" label="品項筆數" /></th>
                  {config.hasApproval && <th style={{ width: 85 }}><SortHead colKey="status" label="狀態" /></th>}
                  <th style={{ width: 120 }} className="center">功能</th>
                </tr>
              ) : (
                <tr>
                  <th style={{ width: 150 }}><SortHead colKey="updatedAt" label="更新時間" /></th>
                  <th style={{ width: 160 }}><SortHead colKey="skuNo" label="品號" /></th>
                  <th><SortHead colKey="name" label={config.nameCol} /></th>
                  {config.extraCols?.map(c => (
                    <th key={c.key} style={c.w ? { width: c.w } : undefined}><SortHead colKey={c.key} label={c.label} /></th>
                  ))}
                  <th style={{ width: 120 }} className="center">功能</th>
                </tr>
              )}
            </thead>
            <tbody>
              {paged.length === 0 ? (
                <tr>
                  <td colSpan={isActivity ? (config.hasApproval ? 7 : 6) : (4 + (config.extraCols?.length || 0))}
                    style={{ textAlign: "center", color: "var(--fg-4)", padding: "40px 0" }}>
                    {q ? `沒有符合「${q}」的資料` : config.emptyTitle}
                  </td>
                </tr>
              ) : isActivity ? paged.map(r => (
                <tr key={r.id}>
                  <td className="mono" style={{ color: "var(--fg-2)" }}>{r.updatedAt}</td>
                  <td><UserChip name={r.applicant} /></td>
                  <td style={{ fontWeight: "var(--fw-medium)" }}>{r.name}</td>
                  <td className="mono" style={{ color: "var(--fg-2)" }}>{r.campaignStart} – {r.campaignEnd}</td>
                  <td className="num">{r.itemCount}</td>
                  {config.hasApproval && <td><Tag status={r.status} /></td>}
                  <td className="center">
                    <RowActions actions={[{ label: "檢視", onClick: viewRow }]} />
                  </td>
                </tr>
              )) : paged.map(r => (
                <tr key={r.id}>
                  <td className="mono" style={{ color: "var(--fg-2)" }}>{r.updatedAt}</td>
                  <td className="mono" style={{ fontSize: "var(--fs-12)" }}>{r.skuNo}</td>
                  <td style={{ fontWeight: "var(--fw-medium)" }}>{r.name}</td>
                  {config.extraCols?.map(c => (
                    <td key={c.key} className={c.mono ? "mono" : undefined} style={c.mono ? { fontSize: "var(--fs-12)" } : undefined}>
                      {c.key === "specialPrice" ? `NT$${Number(r[c.key]).toLocaleString()}` : (r[c.key] || "—")}
                    </td>
                  ))}
                  <td className="center">
                    <RowActions actions={[{ label: "檢視", onClick: viewRow }]} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <Pager total={filtered.length} page={page} pageSize={pageSize}
          onPageChange={setPage} onSizeChange={s => { setPageSize(s); setPage(1); }} />
      </div>
    </>
  );
};

const PROMO_STUB_CONFIG = {
  "p-crm": {
    variant: "activity",
    hasApproval: true,
    subtitle: "CRM 商品活動總表，版型對齊 Collection Offer。",
    addLabel: "新增活動",
    searchPlaceholder: "搜尋活動名稱、申請人…",
    nameCol: "活動名稱",
    emptyTitle: "尚無 CRM 活動",
  },
  "p-page": {
    variant: "activity",
    hasApproval: true,
    subtitle: "專案頁 Collection Page 列表。",
    addLabel: "新增專案頁",
    searchPlaceholder: "搜尋專案頁名稱、申請人…",
    nameCol: "專案頁名稱",
    emptyTitle: "尚無專案頁",
  },
  "p-mg": {
    variant: "activity",
    hasApproval: true,
    subtitle: "商品組合表列表。",
    addLabel: "新增組合",
    searchPlaceholder: "搜尋組合名稱、申請人…",
    nameCol: "組合名稱",
    emptyTitle: "尚無商品組合",
  },
  "p-crm-promo": {
    variant: "item",
    subtitle: "CRM 促銷品項總表。",
    addLabel: "新增促銷品項",
    searchPlaceholder: "搜尋品號、品名…",
    nameCol: "品名",
    emptyTitle: "尚無促銷品項",
    extraCols: [
      { key: "promoType", label: "促銷類型", w: 100 },
      { key: "storeScope", label: "適用門店", w: 100 },
    ],
  },
  "p-timeslot": {
    variant: "item",
    subtitle: "時段特殊價格表。",
    addLabel: "新增時段價格",
    searchPlaceholder: "搜尋品號、品名…",
    nameCol: "品名",
    emptyTitle: "尚無時段特殊價格",
    extraCols: [
      { key: "slot", label: "時段", w: 120 },
      { key: "specialPrice", label: "特殊價格", w: 100, mono: true },
    ],
  },
};

Object.assign(window, { PromoStubList, PROMO_STUB_CONFIG });
