import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import Head from 'next/head';
import DashboardLayout from '../../components/Layout/DashboardLayout';
import { toast } from 'react-hot-toast';
import {
  MagnifyingGlassIcon,
  PlusIcon,
  PencilIcon,
  TrashIcon,
  EyeIcon,
  UserIcon,
  BuildingOfficeIcon,
  PhoneIcon,
  EnvelopeIcon,
  CalendarIcon,
  CheckCircleIcon,
  XCircleIcon,
  ExclamationTriangleIcon,
  ArrowDownTrayIcon,
  FunnelIcon,
  XMarkIcon
} from '@heroicons/react/24/outline';
import { getDemoData } from '../../lib/demo-data';
import { formatTime } from '../../lib/utils';

interface User {
  id: string;
  name: string;
  email: string;
  phone: string;
  company: string;
  role: 'admin' | 'user' | 'interpreter';
  status: 'active' | 'inactive' | 'pending';
  created_at: string;
  last_login: string;
  total_calls: number;
  total_spent: number;
}

interface UserFilters {
  search: string;
  role: string;
  status: string;
  company: string;
}

export default function Users() {
  const router = useRouter();
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [filters, setFilters] = useState<UserFilters>({
    search: '',
    role: '',
    status: '',
    company: ''
  });

  // 添加模态框状态
  const [showAddUserModal, setShowAddUserModal] = useState(false);
  const [newUser, setNewUser] = useState({
    name: '',
    email: '',
    phone: '',
    company: '',
    role: 'user' as 'admin' | 'user' | 'interpreter',
    status: 'active' as 'active' | 'inactive' | 'pending'
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  const pageSize = 10;

  useEffect(() => {
    fetchUsers();
  }, [currentPage, filters]);

  const fetchUsers = async () => {
    try {
      setLoading(true);
      
      // 模拟加载延迟
      await new Promise(resolve => setTimeout(resolve, 800));
      
      // 使用演示数据
      const mockUsers: User[] = [
        {
          id: '1',
          name: '张三',
          email: 'zhangsan@example.com',
          phone: '13800138001',
          company: 'ABC科技有限公司',
          role: 'user',
          status: 'active',
          created_at: '2024-01-15T10:30:00Z',
          last_login: '2024-01-20T14:25:00Z',
          total_calls: 25,
          total_spent: 1250
        },
        {
          id: '2',
          name: '李四',
          email: 'lisi@example.com',
          phone: '13800138002',
          company: 'XYZ贸易公司',
          role: 'user',
          status: 'active',
          created_at: '2024-01-10T09:15:00Z',
          last_login: '2024-01-19T16:45:00Z',
          total_calls: 18,
          total_spent: 890
        },
        {
          id: '3',
          name: '王五',
          email: 'wangwu@example.com',
          phone: '13800138003',
          company: '翻译服务中心',
          role: 'interpreter',
          status: 'active',
          created_at: '2024-01-05T11:20:00Z',
          last_login: '2024-01-20T10:30:00Z',
          total_calls: 156,
          total_spent: 0
        },
        {
          id: '4',
          name: '赵六',
          email: 'zhaoliu@example.com',
          phone: '13800138004',
          company: '管理员',
          role: 'admin',
          status: 'active',
          created_at: '2024-01-01T08:00:00Z',
          last_login: '2024-01-20T18:00:00Z',
          total_calls: 5,
          total_spent: 0
        },
        {
          id: '5',
          name: '孙七',
          email: 'sunqi@example.com',
          phone: '13800138005',
          company: '新用户公司',
          role: 'user',
          status: 'pending',
          created_at: '2024-01-18T15:30:00Z',
          last_login: '',
          total_calls: 0,
          total_spent: 0
        },
        {
          id: '6',
          name: '周八',
          email: 'zhouba@example.com',
          phone: '13800138006',
          company: '暂停用户公司',
          role: 'user',
          status: 'inactive',
          created_at: '2024-01-12T13:45:00Z',
          last_login: '2024-01-15T09:20:00Z',
          total_calls: 8,
          total_spent: 320
        }
      ];

      // 应用过滤器
      let filteredUsers = mockUsers;
      
      if (filters.search) {
        filteredUsers = filteredUsers.filter(user => 
          user.name.toLowerCase().includes(filters.search.toLowerCase()) ||
          user.email.toLowerCase().includes(filters.search.toLowerCase()) ||
          user.company.toLowerCase().includes(filters.search.toLowerCase())
        );
      }
      
      if (filters.role) {
        filteredUsers = filteredUsers.filter(user => user.role === filters.role);
      }
      
      if (filters.status) {
        filteredUsers = filteredUsers.filter(user => user.status === filters.status);
      }
      
      if (filters.company) {
        filteredUsers = filteredUsers.filter(user => 
          user.company.toLowerCase().includes(filters.company.toLowerCase())
        );
      }

      // 分页
      const startIndex = (currentPage - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      const paginatedUsers = filteredUsers.slice(startIndex, endIndex);
      
      setUsers(paginatedUsers);
      setTotalCount(filteredUsers.length);
      setTotalPages(Math.ceil(filteredUsers.length / pageSize));
      
    } catch (error) {
      console.error('Failed to fetch users:', error);
      toast.error('加载用户数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (value: string) => {
    setFilters(prev => ({ ...prev, search: value }));
    setCurrentPage(1);
  };

  const handleFilterChange = (key: keyof UserFilters, value: string) => {
    setFilters(prev => ({ ...prev, [key]: value }));
    setCurrentPage(1);
  };

  const handleSelectUser = (userId: string) => {
    setSelectedUsers(prev => 
      prev.includes(userId) 
        ? prev.filter(id => id !== userId)
        : [...prev, userId]
    );
  };

  const handleSelectAll = () => {
    if (selectedUsers.length === users.length) {
      setSelectedUsers([]);
    } else {
      setSelectedUsers(users.map(user => user.id));
    }
  };

  const handleBulkAction = async (action: string) => {
    if (selectedUsers.length === 0) {
      toast.error('请选择要操作的用户');
      return;
    }

    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      switch (action) {
        case 'activate':
          toast.success(`已激活 ${selectedUsers.length} 个用户`);
          break;
        case 'deactivate':
          toast.success(`已停用 ${selectedUsers.length} 个用户`);
          break;
        case 'delete':
          toast.success(`已删除 ${selectedUsers.length} 个用户`);
          break;
        default:
          break;
      }
      
      setSelectedUsers([]);
      fetchUsers();
    } catch (error) {
      toast.error('操作失败');
    }
  };

  const handleExport = async () => {
    try {
      toast.loading('正在导出用户数据...', { id: 'export' });
      
      // 模拟导出延迟
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      toast.success('用户数据导出成功', { id: 'export' });
    } catch (error) {
      toast.error('导出失败', { id: 'export' });
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active':
        return 'text-green-800 bg-green-100';
      case 'inactive':
        return 'text-red-800 bg-red-100';
      case 'pending':
        return 'text-yellow-800 bg-yellow-100';
      default:
        return 'text-gray-800 bg-gray-100';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'active':
        return '活跃';
      case 'inactive':
        return '停用';
      case 'pending':
        return '待审核';
      default:
        return status;
    }
  };

  const getRoleText = (role: string) => {
    switch (role) {
      case 'admin':
        return '管理员';
      case 'user':
        return '用户';
      case 'interpreter':
        return '翻译员';
      default:
        return role;
    }
  };

  const getRoleColor = (role: string) => {
    switch (role) {
      case 'admin':
        return 'text-purple-800 bg-purple-100';
      case 'user':
        return 'text-blue-800 bg-blue-100';
      case 'interpreter':
        return 'text-green-800 bg-green-100';
      default:
        return 'text-gray-800 bg-gray-100';
    }
  };

  // 添加用户提交函数
  const handleAddUser = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 创建新用户对象
      const newUserData: User = {
        id: Date.now().toString(),
        ...newUser,
        created_at: new Date().toISOString(),
        last_login: '从未登录',
        total_calls: 0,
        total_spent: 0
      };
      
      // 添加到用户列表
      setUsers(prev => [newUserData, ...prev]);
      
      // 重置表单
      setNewUser({
        name: '',
        email: '',
        phone: '',
        company: '',
        role: 'user',
        status: 'active'
      });
      
      // 关闭模态框
      setShowAddUserModal(false);
      
      // 可以添加成功提示
      alert('用户添加成功！');
      
    } catch (error) {
      console.error('添加用户失败:', error);
      alert('添加用户失败，请重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 添加用户模态框组件
  const AddUserModal = () => (
    <div className={`fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 ${showAddUserModal ? 'block' : 'hidden'}`}>
      <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div className="flex justify-between items-center mb-4">
          <h3 className="text-lg font-medium text-gray-900">添加新用户</h3>
          <button
            onClick={() => setShowAddUserModal(false)}
            className="text-gray-400 hover:text-gray-600"
          >
            <XMarkIcon className="h-6 w-6" />
          </button>
        </div>
        
        <form onSubmit={handleAddUser} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              姓名 <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              required
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              value={newUser.name}
              onChange={(e) => setNewUser({...newUser, name: e.target.value})}
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              邮箱 <span className="text-red-500">*</span>
            </label>
            <input
              type="email"
              required
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              value={newUser.email}
              onChange={(e) => setNewUser({...newUser, email: e.target.value})}
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              电话 <span className="text-red-500">*</span>
            </label>
            <input
              type="tel"
              required
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              value={newUser.phone}
              onChange={(e) => setNewUser({...newUser, phone: e.target.value})}
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              公司
            </label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              value={newUser.company}
              onChange={(e) => setNewUser({...newUser, company: e.target.value})}
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              角色 <span className="text-red-500">*</span>
            </label>
            <select
              required
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              value={newUser.role}
              onChange={(e) => setNewUser({...newUser, role: e.target.value as 'admin' | 'user' | 'interpreter'})}
            >
              <option value="user">用户</option>
              <option value="admin">管理员</option>
              <option value="interpreter">翻译员</option>
            </select>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              状态
            </label>
            <select
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              value={newUser.status}
              onChange={(e) => setNewUser({...newUser, status: e.target.value as 'active' | 'inactive' | 'pending'})}
            >
              <option value="active">活跃</option>
              <option value="inactive">停用</option>
              <option value="pending">待审核</option>
            </select>
          </div>
          
          <div className="flex justify-end space-x-3 pt-4">
            <button
              type="button"
              onClick={() => setShowAddUserModal(false)}
              className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50"
            >
              取消
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50"
            >
              {isSubmitting ? '添加中...' : '添加用户'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );

  return (
    <>
      <Head>
        <title>用户管理 - 翻译服务管理系统</title>
      </Head>
      
      <DashboardLayout title="用户管理">
        <div className="space-y-6">
          {/* 页面标题和操作 */}
          <div className="sm:flex sm:items-center sm:justify-between">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">用户管理</h1>
              <p className="mt-2 text-sm text-gray-700">
                管理系统中的所有用户账户，包括用户、翻译员和管理员。
              </p>
            </div>
            <div className="mt-4 sm:mt-0 sm:flex sm:space-x-3">
              <button
                onClick={handleExport}
                className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
              >
                <ArrowDownTrayIcon className="h-4 w-4 mr-2" />
                导出
              </button>
              <button
                onClick={() => setShowAddUserModal(true)}
                className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700"
              >
                <PlusIcon className="h-4 w-4 mr-2" />
                添加用户
              </button>
            </div>
          </div>

          {/* 搜索和过滤器 */}
          <div className="bg-white shadow rounded-lg p-6">
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
              <div>
                <label htmlFor="search" className="block text-sm font-medium text-gray-700 mb-1">
                  搜索
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" />
                  </div>
                  <input
                    type="text"
                    id="search"
                    className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="搜索用户名、邮箱或公司..."
                    value={filters.search}
                    onChange={(e) => handleSearch(e.target.value)}
                  />
                </div>
              </div>

              <div>
                <label htmlFor="role" className="block text-sm font-medium text-gray-700 mb-1">
                  角色
                </label>
                <select
                  id="role"
                  className="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  value={filters.role}
                  onChange={(e) => handleFilterChange('role', e.target.value)}
                >
                  <option value="">全部角色</option>
                  <option value="admin">管理员</option>
                  <option value="user">用户</option>
                  <option value="interpreter">翻译员</option>
                </select>
              </div>

              <div>
                <label htmlFor="status" className="block text-sm font-medium text-gray-700 mb-1">
                  状态
                </label>
                <select
                  id="status"
                  className="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  value={filters.status}
                  onChange={(e) => handleFilterChange('status', e.target.value)}
                >
                  <option value="">全部状态</option>
                  <option value="active">活跃</option>
                  <option value="inactive">停用</option>
                  <option value="pending">待审核</option>
                </select>
              </div>

              <div>
                <label htmlFor="company" className="block text-sm font-medium text-gray-700 mb-1">
                  公司
                </label>
                <input
                  type="text"
                  id="company"
                  className="block w-full py-2 px-3 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  placeholder="过滤公司..."
                  value={filters.company}
                  onChange={(e) => handleFilterChange('company', e.target.value)}
                />
              </div>
            </div>
          </div>

          {/* 批量操作 */}
          {selectedUsers.length > 0 && (
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  <span className="text-sm font-medium text-blue-900">
                    已选择 {selectedUsers.length} 个用户
                  </span>
                </div>
                <div className="flex space-x-2">
                  <button
                    onClick={() => handleBulkAction('activate')}
                    className="inline-flex items-center px-3 py-1 border border-transparent text-xs font-medium rounded text-green-700 bg-green-100 hover:bg-green-200"
                  >
                    <CheckCircleIcon className="h-4 w-4 mr-1" />
                    激活
                  </button>
                  <button
                    onClick={() => handleBulkAction('deactivate')}
                    className="inline-flex items-center px-3 py-1 border border-transparent text-xs font-medium rounded text-yellow-700 bg-yellow-100 hover:bg-yellow-200"
                  >
                    <XCircleIcon className="h-4 w-4 mr-1" />
                    停用
                  </button>
                  <button
                    onClick={() => handleBulkAction('delete')}
                    className="inline-flex items-center px-3 py-1 border border-transparent text-xs font-medium rounded text-red-700 bg-red-100 hover:bg-red-200"
                  >
                    <TrashIcon className="h-4 w-4 mr-1" />
                    删除
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* 用户列表 */}
          <div className="bg-white shadow rounded-lg overflow-hidden">
            {loading ? (
              <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
              </div>
            ) : (
              <>
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-gray-50">
                      <tr>
                        <th scope="col" className="relative px-6 py-3">
                          <input
                            type="checkbox"
                            className="absolute left-4 top-1/2 -mt-2 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                            checked={selectedUsers.length === users.length && users.length > 0}
                            onChange={handleSelectAll}
                          />
                        </th>
                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          用户信息
                        </th>
                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          角色/状态
                        </th>
                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          公司
                        </th>
                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          统计数据
                        </th>
                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          最后登录
                        </th>
                        <th scope="col" className="relative px-6 py-3">
                          <span className="sr-only">操作</span>
                        </th>
                      </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-gray-200">
                      {users.map((user) => (
                        <tr key={user.id} className="hover:bg-gray-50">
                          <td className="relative px-6 py-4">
                            <input
                              type="checkbox"
                              className="absolute left-4 top-1/2 -mt-2 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                              checked={selectedUsers.includes(user.id)}
                              onChange={() => handleSelectUser(user.id)}
                            />
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="flex items-center">
                              <div className="flex-shrink-0 h-10 w-10">
                                <div className="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                                  <UserIcon className="h-6 w-6 text-gray-600" />
                                </div>
                              </div>
                              <div className="ml-4">
                                <div className="text-sm font-medium text-gray-900">{user.name}</div>
                                <div className="text-sm text-gray-500 flex items-center">
                                  <EnvelopeIcon className="h-4 w-4 mr-1" />
                                  {user.email}
                                </div>
                                <div className="text-sm text-gray-500 flex items-center">
                                  <PhoneIcon className="h-4 w-4 mr-1" />
                                  {user.phone}
                                </div>
                              </div>
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="space-y-1">
                              <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getRoleColor(user.role)}`}>
                                {getRoleText(user.role)}
                              </span>
                              <br />
                              <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getStatusColor(user.status)}`}>
                                {getStatusText(user.status)}
                              </span>
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="flex items-center text-sm text-gray-900">
                              <BuildingOfficeIcon className="h-4 w-4 mr-2 text-gray-400" />
                              {user.company}
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <div>通话: {user.total_calls} 次</div>
                            <div>消费: ¥{user.total_spent}</div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <div className="flex items-center">
                              <CalendarIcon className="h-4 w-4 mr-1" />
                              {user.last_login ? formatTime(user.last_login) : '从未登录'}
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <div className="flex items-center space-x-2">
                              <button
                                onClick={() => router.push(`/dashboard/users/${user.id}`)}
                                className="text-blue-600 hover:text-blue-900"
                              >
                                <EyeIcon className="h-4 w-4" />
                              </button>
                              <button
                                onClick={() => router.push(`/dashboard/users/${user.id}/edit`)}
                                className="text-yellow-600 hover:text-yellow-900"
                              >
                                <PencilIcon className="h-4 w-4" />
                              </button>
                              <button
                                onClick={() => {
                                  if (confirm('确定要删除这个用户吗？')) {
                                    toast.success('用户删除成功');
                                  }
                                }}
                                className="text-red-600 hover:text-red-900"
                              >
                                <TrashIcon className="h-4 w-4" />
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* 分页 */}
                {totalPages > 1 && (
                  <div className="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
                    <div className="flex-1 flex justify-between sm:hidden">
                      <button
                        onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                        disabled={currentPage === 1}
                        className="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        上一页
                      </button>
                      <button
                        onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                        disabled={currentPage === totalPages}
                        className="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        下一页
                      </button>
                    </div>
                    <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                      <div>
                        <p className="text-sm text-gray-700">
                          显示第 <span className="font-medium">{(currentPage - 1) * pageSize + 1}</span> 到{' '}
                          <span className="font-medium">{Math.min(currentPage * pageSize, totalCount)}</span> 项，
                          共 <span className="font-medium">{totalCount}</span> 项
                        </p>
                      </div>
                      <div>
                        <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                          <button
                            onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                            disabled={currentPage === 1}
                            className="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            上一页
                          </button>
                          {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                            <button
                              key={page}
                              onClick={() => setCurrentPage(page)}
                              className={`relative inline-flex items-center px-4 py-2 border text-sm font-medium ${
                                page === currentPage
                                  ? 'z-10 bg-blue-50 border-blue-500 text-blue-600'
                                  : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'
                              }`}
                            >
                              {page}
                            </button>
                          ))}
                          <button
                            onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                            disabled={currentPage === totalPages}
                            className="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            下一页
                          </button>
                        </nav>
                      </div>
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </DashboardLayout>

      {/* 添加用户模态框 */}
      <AddUserModal />
    </>
  );
} 