import Add from "@mui/icons-material/Add";
import EditOutlined from "@mui/icons-material/EditOutlined";
import { AdminActionIconButton, AdminRowActions } from "@/shared/ui/AdminListLayout.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { createTextColumnFilter } from "@/shared/ui/tableFilters.js";

export function TeamTable({ abilities, onCreateChild, onEdit, onQueryChange, operationTeamId, pagination, query, teams }) {
  const columns = [
    {
      key: "name",
      label: "团队",
      width: "minmax(180px, 1.2fr)",
      filter: createTextColumnFilter({
        placeholder: "搜索团队名称、ID",
        value: query,
        onChange: onQueryChange
      }),
      render: (team) => (
        <span className={team.parentId ? "team-name-cell team-name-cell--child" : "team-name-cell"}>
          <strong>{team.name}</strong>
          {team.parentName ? <small>{team.parentName}</small> : null}
          {Number(team.id) === Number(operationTeamId) ? <small>运营人员来源</small> : null}
        </span>
      )
    },
    { key: "id", label: "团队 ID", width: "120px", render: (team) => team.id },
    {
      key: "userCount",
      label: "成员数",
      width: "120px",
      render: (team) => Number(team.userCount ?? 0).toLocaleString("en-US")
    },
    { key: "sort", label: "排序", width: "100px", render: (team) => team.sort ?? 0 },
    {
      key: "description",
      label: "说明",
      width: "minmax(240px, 1.5fr)",
      render: (team) => <span className="muted">{team.description || "-"}</span>
    },
    {
      key: "actions",
      label: "操作",
      width: "148px",
      render: (team) => (
        <AdminRowActions>
          {abilities.canCreate && !team.parentId ? (
            <AdminActionIconButton label="新增子部门" onClick={() => onCreateChild(team)}>
              <Add fontSize="inherit" />
            </AdminActionIconButton>
          ) : null}
          {abilities.canUpdate ? (
            <AdminActionIconButton label="编辑" onClick={() => onEdit(team)}>
              <EditOutlined fontSize="inherit" />
            </AdminActionIconButton>
          ) : null}
        </AdminRowActions>
      )
    }
  ];

  return <DataTable columns={columns} items={teams} minWidth="920px" pagination={pagination} rowKey={(team) => team.id} />;
}
