import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Typography, message, Popconfirm, Spin } from 'antd';
import { UserOutlined, UploadOutlined, SettingOutlined } from '@ant-design/icons';
import { getUserList, deleteUser } from '@/api/auth';

const { Title } = Typography;

const AdminPanel = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  
  // 获取管理员信息
  const adminUser = JSON.parse(localStorage.getItem('user') || '{}');
  
  // 加载用户数据
  useEffect(() => {
    fetchUsers();
  }, []);
  
  // 获取用户列表
  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await getUserList(adminUser.username);
      if (response.success) {
        const userList = response.data.users || [];
        // 添加key属性
        const formattedUsers = userList.map(user => ({
          ...user,
          key: user.id,
          role: user.userType === 1 ? '管理员' : '普通用户',
          status: '正常'
        }));
        setUsers(formattedUsers);
      }
    } catch (error) {
      message.error(error.message || '获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };
  
  // 删除用户
  const handleDelete = async (username) => {
    try {
      const response = await deleteUser(adminUser.username, username);
      if (response.success) {
        message.success('用户删除成功');
        fetchUsers(); // 重新加载用户列表
      }
    } catch (error) {
      message.error(error.message || '删除用户失败');
    }
  };

  const columns = [
    { title: '用户名', dataIndex: 'username', key: 'username' },
    { title: '角色', dataIndex: 'role', key: 'role' },
    { title: '状态', dataIndex: 'status', key: 'status' },
    { title: '注册日期', dataIndex: 'createTime', key: 'createTime' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link">编辑</Button>
          {record.userType !== 1 && (
            <Popconfirm
              title="确定要删除该用户吗？"
              onConfirm={() => handleDelete(record.username)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="link" danger>删除</Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="p-6">
      <Title level={2}>管理员控制面板</Title>
      <div className="flex gap-4 mb-6">
        <Card title="用户统计" className="w-1/3">
          <div className="flex items-center">
            <UserOutlined className="text-2xl mr-2" />
            <span className="text-xl">{users.length} 名用户</span>
          </div>
        </Card>
        <Card title="资源统计" className="w-1/3">
          <div className="flex items-center">
            <UploadOutlined className="text-2xl mr-2" />
            <span className="text-xl">25 个资源</span>
          </div>
        </Card>
        <Card title="系统状态" className="w-1/3">
          <div className="flex items-center">
            <SettingOutlined className="text-2xl mr-2" />
            <span className="text-xl">运行正常</span>
          </div>
        </Card>
      </div>
      <Card title="用户管理">
        {loading ? (
          <div className="flex justify-center py-8">
            <Spin size="large" tip="加载中..." />
          </div>
        ) : (
          <Table columns={columns} dataSource={users} />
        )}
      </Card>
    </div>
  );
};

export default AdminPanel;