/* global React, Icon, Button, Tag, Pager, useToast, PAGE_SIZES, FilterBar, PageHead, RowActions, UserChip, useSortableTable, isPrototypeSuperUser, canActAsPurchase, canActAsJoanna */
// Collection Offer L1 — 滿額折／滿件折 活動列表

const { useState, useMemo } = React;

const CollectionOfferList = ({ offers, hasApproval, role, currentUser, sectionLabel, titleLabel, onCreate, onOpen, onDelete, onToggleStatus }) => {
  const [fDateFrom,   setFDateFrom]   = useState("");
  const [fDateTo,     setFDateTo]     = useState("");
  const [fType,       setFType]       = useState([]);
  const [fStatus,     setFStatus]     = useState([]);
  const [fApplicant,  setFApplicant]  = useState([]);
  const [page,        setPage]        = useState(1);
  const [pageSize,    setPageSize]    = useState(PAGE_SIZES[0]);
  const { SortHead, applySortTo }    = useSortableTable("updatedAt", "desc");
  const { push: toast } = useToast();

  // 審核者身份只有在「有審核流程」時才生效：hasApproval=false → Joanna 退化為一般檢視者，
  // 所有審核專屬 UI（審核中提示帶、進入審核操作、排除草稿篩選）一併消失。
  const isReviewer = hasApproval && canActAsJoanna(role) && !isPrototypeSuperUser(role);

  // 申請人選項 = 可見集合（所有非草稿 + 自己的草稿）的建立者
  const allApplicants = useMemo(() =>
    [...new Set(
      offers.filter(o => o.status !== "coDraft" || o.applicant === currentUser)
            .map(o => o.applicant)
    )].filter(Boolean).sort(),
    [offers, currentUser]
  );

  const filtered = useMemo(() => offers.filter(o => {
    if (!isPrototypeSuperUser(role)) {
      if (canActAsPurchase(role) && !canActAsJoanna(role) && o.status === "coDraft" && o.applicant !== currentUser) return false;
      if (isReviewer && o.status === "coDraft") return false;
    }
    if (fType.length      && !fType.includes(o.type))       return false;
    if (fStatus.length    && !fStatus.includes(o.status))   return false;
    if (fApplicant.length && !fApplicant.includes(o.applicant)) return false;
    if (fDateFrom && o.campaignEnd   < fDateFrom)           return false;
    if (fDateTo   && o.campaignStart > fDateTo)             return false;
    return true;
  }), [offers, role, isReviewer, currentUser, fType, fStatus, fApplicant, fDateFrom, fDateTo]);

  const sorted = useMemo(() => applySortTo(filtered, (o, key) =>
    key === "items" ? o.items.length : (o[key] ?? "")
  ), [filtered, applySortTo]);

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

  const pendingCount = useMemo(() => {
    if (!hasApproval || !canActAsJoanna(role)) return 0;
    return offers.filter(o => o.status === "coUnderReview").length;
  }, [offers, hasApproval, role]);

  const getActions = (o) => {
    if (isPrototypeSuperUser(role)) {
      const actions = [];
      if (o.status === "coUnderReview") actions.push({ label: "進入審核", onClick: () => onOpen(o) });
      if (o.status === "coDraft" || o.status === "coRejected") {
        actions.push({ label: "編輯", onClick: () => onOpen(o) });
        actions.push({ label: "刪除", danger: true, onClick: () => onDelete(o) });
      } else if (o.status === "coApproved" || o.status === "coNoReview") {
        actions.push({ label: "編輯", onClick: () => onOpen(o) });
      }
      if (actions.length) return actions;
      return [{ label: "檢視", onClick: () => onOpen(o) }];
    }
    if (canActAsPurchase(role)) {
      const isApplicant = o.applicant === currentUser;
      if (!isApplicant)                   return [{ label: "檢視",   onClick: () => onOpen(o) }];
      if (o.status === "coDraft" || o.status === "coRejected") return [
        { label: "編輯", onClick: () => onOpen(o) },
        { label: "刪除", danger: true, onClick: () => onDelete(o) },
      ];
      if (o.status === "coUnderReview")   return [{ label: "檢視",   onClick: () => onOpen(o) }];
      if (o.status === "coApproved" || o.status === "coNoReview") return [{ label: "編輯", onClick: () => onOpen(o) }];
      return [{ label: "檢視", onClick: () => onOpen(o) }];
    }
    if (isReviewer) {
      if (o.status === "coUnderReview")   return [{ label: "進入審核", onClick: () => onOpen(o) }];
      return [{ label: "檢視", onClick: () => onOpen(o) }];
    }
    return [{ label: "檢視", onClick: () => onOpen(o) }];
  };

  const typeLabel = (t) => t === "BxFy" ? "滿件折" : "滿額折";

  return (
    <>
      <PageHead
        section={sectionLabel}
        title={titleLabel}
        subtitle={hasApproval
          ? "設定 Uber Eats 專區滿額折與滿件折活動，提交後依送審條件判斷是否進入人工審核。"
          : "設定 Uber Eats 專區滿額折與滿件折活動。"}
        actions={canActAsPurchase(role) && (
          <Button variant="primary" icon="plus" onClick={onCreate}>新增活動</Button>
        )}
      />

      {(canActAsJoanna(role) && pendingCount > 0) && (
        <div className="summary-strip">
          <span className="summary-strip__label">待審核</span>
          <span className="summary-strip__num">{pendingCount} 筆</span>
        </div>
      )}

      <FilterBar
        filters={[
          {
            type: "dateRange", label: "活動期間",
            from: fDateFrom, to: fDateTo,
            onApply: (f, t) => { setFDateFrom(f); setFDateTo(t); setPage(1); },
          },
          {
            type: "chip", label: "類型", multi: true,
            value: fType,
            options: [{ value: "BxFy", label: "滿件折" }, { value: "SxSy", label: "滿額折" }],
            onChange: v => { setFType(v); setPage(1); },
          },
          ...(hasApproval ? [{
            type: "chip", label: "狀態", multi: true,
            value: fStatus,
            options: [
              { value: "coDraft",       label: "草稿" },
              { value: "coUnderReview", label: "待審核" },
              { value: "coNoReview",    label: "無需審核" },
              { value: "coApproved",    label: "審核通過" },
              { value: "coRejected",    label: "已退回" },
            ],
            onChange: v => { setFStatus(v); setPage(1); },
          }] : []),
          // 申請人篩選對所有角色開放（co-2 全採購可見，採購也需要能篩）
          {
            type: "chip", label: "申請人", multi: true,
            value: fApplicant,
            options: allApplicants.map(a => ({ value: a, label: a })),
            onChange: v => { setFApplicant(v); setPage(1); },
          },
        ]}
      />

      <div className="card">
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th style={{ width: 150 }}><SortHead colKey="updatedAt" label="更新時間" /></th>
                <th style={{ width: 100 }}><SortHead colKey="applicant" label="申請人" /></th>
                <th><SortHead colKey="name" label="活動名稱" /></th>
                <th style={{ width: 80 }}><SortHead colKey="type" label="類型" /></th>
                <th style={{ width: 210 }}><SortHead colKey="campaignStart" label="活動期間" /></th>
                <th style={{ width: 120 }}><SortHead colKey="createdAt" label="建立日期" /></th>
                <th style={{ width: 85 }} className="num"><SortHead colKey="items" label="品項筆數" /></th>
                {hasApproval && <th style={{ width: 85 }}><SortHead colKey="status" label="狀態" /></th>}
                <th style={{ width: 150 }} className="center">功能</th>
              </tr>
            </thead>
            <tbody>
              {paged.length === 0 && (
                <tr>
                  <td colSpan={hasApproval ? 9 : 8}>
                    <div className="empty" style={{ padding: "40px 20px" }}>
                      <div className="empty__icon"><Icon name="tag" size={36} /></div>
                      <div className="empty__title">沒有符合條件的活動</div>
                      <div className="empty__desc">試試清除篩選條件，或點右上角「新增活動」。</div>
                    </div>
                  </td>
                </tr>
              )}
              {paged.map(o => (
                <tr key={o.id}>
                  <td className="mono" style={{ color: "var(--fg-2)" }}>{o.updatedAt}</td>
                  <td><UserChip name={o.applicant} /></td>
                  <td>
                    <a className="tbl-link" onClick={() => onOpen(o)}>{o.name}</a>
                    <div className="mono" style={{ fontSize: 11, color: "var(--fg-3)", marginTop: 2 }}>{o.scheme}</div>
                  </td>
                  <td><Tag variant="teal">{typeLabel(o.type)}</Tag></td>
                  <td className="mono" style={{ color: "var(--fg-2)" }}>{o.campaignStart} – {o.campaignEnd}</td>
                  <td className="mono" style={{ color: "var(--fg-2)" }}>{o.createdAt}</td>
                  <td className="num">{o.items.length}</td>
                  {hasApproval && <td><Tag status={o.status} /></td>}
                  <td className="center"><RowActions actions={getActions(o)} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <Pager
          total={sorted.length} page={page} pageSize={pageSize}
          pageSizeOptions={PAGE_SIZES}
          onPage={setPage}
          onPageSize={p => { setPageSize(p); setPage(1); }}
        />
      </div>
    </>
  );
};
