// User list — searchable/filterable table.

const UserList = ({ users, onOpenUser, onCreateUser }) => {
  const [scope, setScope] = React.useState("all");
  const [field, setField] = React.useState("empName");
  const [matchMode, setMatchMode] = React.useState("contains");
  const [query, setQuery] = React.useState("");
  const [selected, setSelected] = React.useState(null);
  const [checkedRows, setCheckedRows] = React.useState({});
  const [sort, setSort] = React.useState({ key: null, dir: "asc" });

  const toggleRow = (id) => setCheckedRows((s) => ({ ...s, [id]: !s[id] }));
  const checkedCount = Object.values(checkedRows).filter(Boolean).length;

  const filtered = React.useMemo(() => {
    let rows = users;
    if (scope === "active") rows = rows.filter((u) => !u.disabled);
    if (scope === "disabled") rows = rows.filter((u) => u.disabled);
    if (query) {
      const q = query.toLowerCase();
      const cmp = (a, b) => {
        if (matchMode === "exact") return a === b;
        if (matchMode === "starts") return a.startsWith(b);
        return a.includes(b);
      };
      rows = rows.filter((u) => {
        const v = String(u[field === "empName" ? "employee" : field === "account" ? "account" : field === "empNo" ? "empNo" : field === "department" ? "department" : "employee"] || "").toLowerCase();
        return cmp(v, q);
      });
    }
    if (sort.key) {
      const dir = sort.dir === "asc" ? 1 : -1;
      rows = [...rows].sort((a, b) => String(a[sort.key]).localeCompare(String(b[sort.key]), "zh") * dir);
    }
    return rows;
  }, [users, scope, query, field, matchMode, sort]);

  const toggleSort = (k) => setSort((s) => ({ key: k, dir: s.key === k && s.dir === "asc" ? "desc" : "asc" }));

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", background: "var(--bg-app)" }}>
      {/* Filter toolbar */}
      <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "6px 8px", background: "#eaf1f7", borderBottom: "1px solid var(--border)", flex: "none" }}>
        <ToolbarBtnLight icon={<Ic.refresh size={12} />}>刷新</ToolbarBtnLight>
        <ToolbarBtnLight icon={<Ic.plus size={12} />} primary onClick={onCreateUser}>新增</ToolbarBtnLight>
        <ToolbarBtnLight icon={<Ic.export size={12} />}>导出 Excel</ToolbarBtnLight>
        <span style={{ width: 1, height: 18, background: "var(--border)", margin: "0 2px" }} />
        <select value={scope} onChange={(e) => setScope(e.target.value)} style={selectStyle}>
          <option value="all">全部用户</option>
          <option value="active">启用用户</option>
          <option value="disabled">禁用用户</option>
        </select>
        <select value={field} onChange={(e) => setField(e.target.value)} style={selectStyle}>
          <option value="empName">员工名</option>
          <option value="account">用户名</option>
          <option value="empNo">用户号</option>
          <option value="department">部门</option>
        </select>
        <select value={matchMode} onChange={(e) => setMatchMode(e.target.value)} style={selectStyle}>
          <option value="contains">包含</option>
          <option value="starts">开头是</option>
          <option value="exact">完全匹配</option>
        </select>
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder=""
          style={{ height: 26, width: 180, border: "1px solid var(--border-input)", padding: "0 6px", fontSize: 12, background: "var(--bg-input)" }}
        />
        <ToolbarBtnLight icon={<Ic.search size={12} />} primary>查 找</ToolbarBtnLight>
        <ToolbarBtnLight onClick={() => { setQuery(""); setScope("all"); }}>清 空</ToolbarBtnLight>
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 11, color: "var(--text-muted)" }}>
          {checkedCount > 0 ? <>已选 <span style={{ color: "var(--accent-strong)", fontWeight: 500 }}>{checkedCount}</span> 条 / </> : null}
          共 {users.length} 条记录
        </span>
      </div>

      {/* Table */}
      <div style={{ flex: 1, overflow: "auto", background: "#fff" }}>
        <table style={{ borderCollapse: "collapse", width: "100%", fontSize: 12, tableLayout: "fixed" }}>
          <colgroup>
            <col style={{ width: 32 }} />
            <col style={{ width: 50 }} />
            {colDefs.map((c) => <col key={c.key} style={{ width: c.w }} />)}
          </colgroup>
          <thead>
            <tr style={{ background: "var(--bg-row-zebra)", borderBottom: "1px solid var(--border)" }}>
              <th style={thStyle}>
                <Checkbox
                  checked={filtered.length > 0 && filtered.every((u) => checkedRows[u.id])}
                  onChange={(v) => {
                    const next = { ...checkedRows };
                    filtered.forEach((u) => { next[u.id] = v; });
                    setCheckedRows(next);
                  }}
                />
              </th>
              <th style={thStyle} onClick={() => toggleSort("seq")}>序号</th>
              {colDefs.map((c) => (
                <th key={c.key} style={{ ...thStyle, cursor: "pointer" }} onClick={() => toggleSort(c.key)}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 3 }}>
                    {c.label}
                    {sort.key === c.key ? (
                      <span style={{ color: "var(--accent)" }}>
                        {sort.dir === "asc" ? <Ic.triangle size={8} /> : <Ic.triangle size={8} style={{ transform: "rotate(180deg)" }} />}
                      </span>
                    ) : (
                      <span style={{ color: "var(--text-faint)", opacity: 0.4 }}><Ic.triangle size={8} /></span>
                    )}
                  </span>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filtered.map((u, idx) => {
              const isSel = selected === u.id;
              return (
                <tr
                  key={u.id}
                  onClick={() => setSelected(u.id)}
                  onDoubleClick={() => onOpenUser(u)}
                  style={{
                    background: isSel ? "var(--selected)" : idx % 2 === 0 ? "#fff" : "var(--bg-row-zebra)",
                    cursor: "pointer", height: 24,
                    color: u.disabled ? "var(--text-faint)" : "var(--text)",
                  }}
                  onMouseEnter={(e) => { if (!isSel) e.currentTarget.style.background = "var(--bg-row-hover)"; }}
                  onMouseLeave={(e) => { if (!isSel) e.currentTarget.style.background = idx % 2 === 0 ? "#fff" : "var(--bg-row-zebra)"; }}
                >
                  <td style={tdStyle} onClick={(e) => e.stopPropagation()}>
                    <Checkbox checked={!!checkedRows[u.id]} onChange={() => toggleRow(u.id)} />
                  </td>
                  <td style={{ ...tdStyle, fontFamily: '"JetBrains Mono", Menlo, monospace', color: "var(--text-muted)" }}>{u.seq}</td>
                  <td style={tdStyle}>{u.employee}</td>
                  <td style={tdStyle}>{u.empNo}</td>
                  <td style={{ ...tdStyle, fontFamily: '"JetBrains Mono", Menlo, monospace' }}>{u.account}</td>
                  <td style={tdStyle}>{u.department}</td>
                  <td style={tdStyle}>{u.type}</td>
                  <td style={tdStyle}>{u.language}</td>
                  <td style={tdStyle}>
                    <Checkbox checked={u.disabled} disabled />
                  </td>
                  <td style={{ ...tdStyle, fontFamily: '"JetBrains Mono", Menlo, monospace', fontSize: 11 }}>{u.lastLogin}</td>
                  <td style={tdStyle}>{u.createdBy}</td>
                  <td style={{ ...tdStyle, fontFamily: '"JetBrains Mono", Menlo, monospace', fontSize: 11 }}>{u.createdAt}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {filtered.length === 0 ? (
          <div style={{ padding: 32, textAlign: "center", color: "var(--text-faint)", fontSize: 12 }}>
            没有匹配的记录
          </div>
        ) : null}
      </div>

      {/* Footer */}
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "6px 12px", background: "#fff", borderTop: "1px solid var(--border)", flex: "none",
        fontSize: 11, color: "var(--text-muted)",
      }}>
        <span>当前显示：共 {filtered.length} 条单据  共 {filtered.length} 条记录</span>
        <div style={{ display: "flex", gap: 4, alignItems: "center" }}>
          <button style={pgBtn} disabled><Ic.chevronLeft size={10} /></button>
          <span style={{ background: "var(--accent)", color: "#fff", padding: "2px 8px", fontSize: 11 }}>1</span>
          <button style={pgBtn} disabled><Ic.chevronRight size={10} /></button>
          <select style={{ ...selectStyle, height: 22, marginLeft: 8 }}>
            <option>10000 条/页</option>
            <option>500 条/页</option>
            <option>100 条/页</option>
          </select>
        </div>
      </div>
    </div>
  );
};

const colDefs = [
  { key: "employee", label: "员工名", w: 100 },
  { key: "empNo", label: "员工号", w: 90 },
  { key: "account", label: "用户号", w: 90 },
  { key: "department", label: "部门", w: 110 },
  { key: "type", label: "用户类型", w: 110 },
  { key: "language", label: "语言", w: 60 },
  { key: "disabled", label: "作废", w: 50 },
  { key: "lastLogin", label: "登录日期", w: 145 },
  { key: "createdBy", label: "制单人", w: 90 },
  { key: "createdAt", label: "制单日期", w: 145 },
];

const selectStyle = {
  height: 26, padding: "0 6px", border: "1px solid var(--border-input)",
  background: "#fff", fontSize: 12, color: "var(--text)", fontFamily: "inherit",
};

const thStyle = {
  padding: "5px 8px", textAlign: "left", fontWeight: 500,
  borderRight: "1px solid var(--border)", borderBottom: "1px solid var(--border)",
  whiteSpace: "nowrap",
};

const tdStyle = {
  padding: "3px 8px", borderRight: "1px solid var(--border)", borderBottom: "1px solid #f0f2f5",
  whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
};

const pgBtn = {
  width: 22, height: 22, border: "1px solid var(--border-input)", background: "#fff", cursor: "pointer",
  display: "inline-flex", alignItems: "center", justifyContent: "center",
};

window.UserList = UserList;
