/* global React, Icon, Button, Tag, PageHead, StatusSwitch, FilterBar,
   APPROVAL_FORMS, COND_TYPES, getOperator, getFieldType, useSortableTable */
// 審核流程設定 — L1 列表

const { useState, useMemo } = React;

// ---------- helpers ----------
const opLabel = (fieldName, opId) => getOperator(fieldName, opId).label;

// One rule → human string
const ruleText = (r) => {
  const op = opLabel(r.field, r.op);
  const shape = getOperator(r.field, r.op).valueShape;
  if (shape === "none") return `${r.field} ${op}`;
  const isPct = getFieldType(r.field) === "percent";
  const v = String(r.value ?? "");
  return `${r.field} ${op} ${v}${isPct && v ? "%" : ""}`;
};

// Format single approver chip for display
const approverChips = (step) => {
  const v = (step.values || [])[0];
  if (!v) return null;
  return <span className={"af-approver af-approver--" + step.type}>{v}</span>;
};

// ---------- main ----------
const ApprovalList = ({ flows, onCreate, onEdit, onToggle, onDuplicate }) => {
  const [q, setQ] = useState("");
  const [filterForm, setFilterForm] = useState("");
  const [filterCond, setFilterCond] = useState("");
  const [filterEnabled, setFilterEnabled] = useState("");
  const { SortHead, applySortTo } = useSortableTable("updated", "desc");

  const filtered = useMemo(() => {
    let r = flows;
    const needle = q.trim().toLowerCase();
    if (needle) {
      r = r.filter((f) =>
        f.name.toLowerCase().includes(needle) ||
        f.formLabel.toLowerCase().includes(needle) ||
        f.rules.some((rr) => ruleText(rr).toLowerCase().includes(needle)) ||
        f.steps.some((ss) => (ss.values || []).join(",").toLowerCase().includes(needle))
      );
    }
    if (filterForm) r = r.filter((f) => f.formId === filterForm);
    if (filterCond) r = r.filter((f) => f.condType === filterCond);
    if (filterEnabled) r = r.filter((f) => (filterEnabled === "on") === f.enabled);
    return applySortTo(r);
  }, [flows, q, filterForm, filterCond, filterEnabled, applySortTo]);

  return (
    <>
      <PageHead
        section="帳號與權限"
        title="審核流程與條件設定"
        subtitle="管理各表單的審核規則與審核者；每張表單設定一條審核流程，送出後依步驟順序逐關簽核。"
        actions={
          <Button variant="primary" icon="plus" onClick={onCreate}>新增流程</Button>
        }
      />

      <FilterBar
        filters={[
          { type: "search", placeholder: "搜尋名稱、表單、審核人、規則…", value: q, onChange: v => setQ(v) },
          { type: "chip", label: "作用表單", value: filterForm, options: APPROVAL_FORMS.map(f => ({ value: f.id, label: f.label })), onChange: setFilterForm },
          { type: "chip", label: "條件類型", value: filterCond, options: COND_TYPES.map(c => ({ value: c.id, label: c.label })), onChange: setFilterCond },
          { type: "chip", label: "狀態", value: filterEnabled, options: [{ value: "on", label: "啟用中" }, { value: "off", label: "已停用" }], onChange: setFilterEnabled },
        ]}
      />

      <div className="card">
        <div className="toolbar">
          <span className="af-tbl-count">
            共 <b>{filtered.length}</b> / {flows.length} 條規則
          </span>
        </div>
        <div className="tbl-wrap">
          <table className="tbl af-tbl">
            <thead>
              <tr>
                <th style={{ width: 150 }} className="th-e"><SortHead colKey="updated" label="更新時間" /></th>
                <th style={{ width: 180 }} className="th-a"><SortHead colKey="name" label="名稱" /></th>
                <th style={{ width: 200 }} className="th-a"><SortHead colKey="formLabel" label="作用表單" /></th>
                <th style={{ width: 100 }} className="th-b"><SortHead colKey="condType" label="條件類型" /></th>
                <th style={{ width: 220 }} className="th-c">審核流程步驟</th>
                <th className="th-d">規則設定</th>
                <th style={{ width: 92 }} className="th-e center"><SortHead colKey="enabled" label="狀態" /></th>
                <th style={{ width: 120 }} className="center">功能</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((f) => {
                return (
                  <tr key={f.id}>
                    <td className="mono" style={{ color: "var(--fg-2)" }}>{f.updated}</td>
                    <td>
                      <a className="tbl-link" onClick={() => onEdit(f)}>{f.name}</a>
                      <span className="af-id">{f.id}</span>
                    </td>
                    <td>{f.formLabel}</td>
                    <td>
                      <Tag status={f.condType === "field" ? "condField" : "condAll"} />
                    </td>
                    <td>
                      <div className="af-steplist">
                        {f.steps.map((s, i) =>
                        <div key={i} className="af-step">
                            {f.steps.length > 1 && <span className="af-step__t">Step{i + 1}</span>}
                            <span className="af-step__t">{s.type === "role" ? "指定職位" : "指定人員"}</span>
                            <span className="af-approvers">{approverChips(s)}</span>
                          </div>
                        )}
                      </div>
                    </td>
                    <td>
                      {f.condType === "all" ?
                      <span className="cell-empty">無條件（一律觸發）</span> :
                      f.rules.length === 0 ?
                      <span className="cell-empty">—</span> :

                      <div>
                              <span className={"af-combi af-combi--" + (f.combinator || "and")}>
                                {f.combinator === "or" ? "任一成立 OR" : "全部成立 AND"}
                              </span>
                              <ul className="af-rules">
                                {f.rules.map((r, i) => <li key={i}>{ruleText(r)}</li>)}
                              </ul>
                            </div>
                      }
                    </td>
                    <td className="center">
                      <StatusSwitch on={f.enabled} onClick={() => onToggle(f)} />
                    </td>
                    <td className="center">
                      <span className="actions">
                        <Button variant="text" size="sm" onClick={() => onEdit(f)}>編輯</Button>
                        <Button variant="text" size="sm" onClick={() => onDuplicate(f)}>複製</Button>
                      </span>
                    </td>
                  </tr>);

              })}
              {filtered.length === 0 &&
              <tr><td colSpan={8}>
                  <div className="empty">
                    <div className="empty__icon"><Icon name="shield" size={56} /></div>
                    <div className="empty__title">沒有符合條件的審核流程</div>
                    <div className="empty__desc">放寬篩選條件，或新增一條新的規則。</div>
                    <Button variant="primary" icon="plus" onClick={onCreate}>新增審核流程</Button>
                  </div>
                </td></tr>
              }
            </tbody>
          </table>
        </div>
      </div>
    </>);

};

Object.assign(window, { ApprovalList, ruleText });
