import EditOutlined from "@mui/icons-material/EditOutlined";
import LockOutlined from "@mui/icons-material/LockOutlined";
import LockOpenOutlined from "@mui/icons-material/LockOpenOutlined";
import PasswordOutlined from "@mui/icons-material/PasswordOutlined";
import Person from "@mui/icons-material/Person";
import PersonRemoveOutlined from "@mui/icons-material/PersonRemoveOutlined";
import VerifiedUserOutlined from "@mui/icons-material/VerifiedUserOutlined";
import Checkbox from "@mui/material/Checkbox";
import { AdminActionIconButton, AdminRowActions } from "@/shared/ui/AdminListLayout.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { createOptionsColumnFilter, createTextColumnFilter } from "@/shared/ui/tableFilters.js";
import { formatMillis } from "@/shared/utils/time.js";
import { UserStatusBadge } from "./UserStatusBadge.jsx";

export function UserTable({
  canEdit,
  canResetPassword,
  canStatus,
  onEdit,
  onOpenProfile = () => {},
  onQueryChange,
  onResetPassword,
  onRoleFilterChange,
  onStatusFilterChange,
  onToggleDisabled,
  onToggleLocked,
  pagination,
  query,
  roleFilter,
  roleFilters = [],
  selectedIds,
  setSelectedIds,
  statusFilter,
  statusFilters = [],
  users
}) {
  const allChecked = users.length > 0 && users.every((user) => selectedIds.includes(user.id));

  const toggleAll = (checked) => {
    if (!checked) {
      setSelectedIds([]);
      return;
    }
    setSelectedIds(users.map((user) => user.id));
  };
  const columns = [
    {
      key: "select",
      header: <Checkbox checked={allChecked} onChange={(event) => toggleAll(event.target.checked)} size="small" />,
      width: "48px",
      render: (user) => (
        <Checkbox
          checked={selectedIds.includes(user.id)}
          onChange={(event) => {
            setSelectedIds((current) => (event.target.checked ? [...current, user.id] : current.filter((id) => id !== user.id)));
          }}
          size="small"
        />
      )
    },
    {
      key: "user",
      label: "用户",
      width: "minmax(180px, 1.4fr)",
      filter: createTextColumnFilter({
        placeholder: "搜索用户、账号、角色、团队",
        value: query,
        onChange: onQueryChange
      }),
      render: (user) => (
        <button
          aria-label={`查看 ${user.name || user.account || user.id} 信息`}
          className="user-main-button"
          type="button"
          onClick={() => onOpenProfile(user)}
        >
          <span className="user-main">
            <span className="user-avatar">
              <Person fontSize="small" />
            </span>
            <span className="user-main__text">
              <span className="service-name">{user.name}</span>
              <span className="service-desc">{user.account}</span>
            </span>
          </span>
        </button>
      )
    },
    {
      key: "role",
      label: "角色",
      width: "minmax(120px, 1fr)",
      filter: createOptionsColumnFilter({
        options: roleFilters,
        placeholder: "搜索角色",
        value: roleFilter,
        onChange: onRoleFilterChange
      }),
      render: (user) => user.role || "-"
    },
    { key: "team", label: "团队", width: "minmax(120px, 1fr)", render: (user) => user.teamName || user.team || "-" },
    {
      key: "status",
      label: "状态",
      width: "minmax(96px, 0.72fr)",
      filter: createOptionsColumnFilter({
        options: statusFilters,
        placeholder: "搜索状态",
        value: statusFilter,
        onChange: onStatusFilterChange
      }),
      render: (user) => <UserStatusBadge status={user.status} />
    },
    { key: "mfa", label: "MFA", width: "minmax(80px, 0.72fr)" },
    {
      key: "lastLogin",
      label: "最后登录",
      width: "minmax(170px, 0.9fr)",
      className: "muted",
      render: (user) => formatMillis(user.lastLoginMs ?? user.lastLoginAtMs ?? user.lastLogin)
    },
    {
      key: "actions",
      label: "操作",
      width: "minmax(180px, 1.2fr)",
      render: (user) => (
        <UserRowActions
          canEdit={canEdit}
          canResetPassword={canResetPassword}
          canStatus={canStatus}
          onEdit={onEdit}
          onResetPassword={onResetPassword}
          onToggleDisabled={onToggleDisabled}
          onToggleLocked={onToggleLocked}
          user={user}
        />
      )
    }
  ];

  return (
    <DataTable
      columns={columns}
      items={users}
      minWidth="1180px"
      pagination={pagination}
      rowKey={(user) => user.id}
    />
  );
}

function UserRowActions({
  canEdit,
  canResetPassword,
  canStatus,
  onEdit,
  onResetPassword,
  onToggleDisabled,
  onToggleLocked,
  user
}) {
  const isDisabled = user.status === "disabled";
  const isLocked = user.status === "locked";

  return (
    <AdminRowActions>
      <AdminActionIconButton disabled={!canEdit} label="编辑" onClick={() => onEdit(user)}>
        <EditOutlined fontSize="inherit" />
      </AdminActionIconButton>
      <AdminActionIconButton disabled={!canResetPassword} label="重置密码" onClick={() => onResetPassword(user)}>
        <PasswordOutlined fontSize="inherit" />
      </AdminActionIconButton>
      <AdminActionIconButton
        disabled={!canStatus || isDisabled}
        label={isLocked ? "解锁" : "锁定"}
        onClick={() => onToggleLocked(user)}
        tone={isLocked ? "success" : undefined}
      >
        {isLocked ? <LockOpenOutlined fontSize="inherit" /> : <LockOutlined fontSize="inherit" />}
      </AdminActionIconButton>
      <AdminActionIconButton
        disabled={!canStatus}
        label={isDisabled ? "启用" : "停用"}
        onClick={() => onToggleDisabled(user)}
        tone={isDisabled ? "success" : "danger"}
      >
        {isDisabled ? <VerifiedUserOutlined fontSize="inherit" /> : <PersonRemoveOutlined fontSize="inherit" />}
      </AdminActionIconButton>
    </AdminRowActions>
  );
}
