import React, { useState } from 'react';
import { Card, Typography, Table, Button, Form, Input, Select, Modal, message, Popconfirm } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { Link } from 'umi';
import { settingsDataSource, User } from '@/services/settingsDataSource';

const { Title, Text } = Typography;
const { Option } = Select;
const { Item } = Form;

const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<User[]>([
    {
      id: '1',
      username: 'admin',
      nickname: '管理员',
      email: 'admin@example.com',
      phone: '13800138000',
      role: 'ADMIN',
      status: 'active',
      createdAt: '2026-03-01',
      lastLogin: '2026-03-18 10:30',
    },
    {
      id: '2',
      username: 'manager',
      nickname: '运营主管',
      email: 'manager@example.com',
      phone: '13800138001',
      role: 'MANAGER',
      status: 'active',
      createdAt: '2026-03-02',
      lastLogin: '2026-03-18 09:15',
    },
    {
      id: '3',
      username: 'operator',
      nickname: '运营专员',
      email: 'operator@example.com',
      phone: '13800138002',
      role: 'OPERATOR',
      status: 'active',
      createdAt: '2026-03-03',
      lastLogin: '2026-03-17 16:45',
    },
  ]);

  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm();

  const handleAddUser = () => {
    setEditingUser(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEditUser = (user: User) => {
    setEditingUser(user);
    form.setFieldsValue(user);
    setIsModalVisible(true);
  };

  const handleDeleteUser = (id: string) => {
    const updatedUsers = users.filter(user => user.id !== id);
    setUsers(updatedUsers);
    message.success('用户已删除');
  };

  const handleSaveUser = () => {
    form.validateFields().then(values => {
      if (editingUser) {
        const updatedUsers = users.map(user => 
          user.id === editingUser.id ? { ...user, ...values } : user
        );
        setUsers(updatedUsers);
        message.success('用户信息已更新');
      } else {
        const newUser: User = {
          id: (users.length + 1).toString(),
          ...values,
          status: 'active',
          createdAt: new Date().toISOString().split('T')[0],
          lastLogin: '-',
        };
        setUsers([...users, newUser]);
        message.success('用户已添加');
      }
      setIsModalVisible(false);
    });
  };

  const columns = [
    {
      title: '用户ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role: string) => (
        <span>
          {role === 'ADMIN' ? '管理员' : 
           role === 'MANAGER' ? '运营主管' : 
           role === 'OPERATOR' ? '运营专员' : 
           role === 'FINANCE' ? '财务主管' : 
           role === 'SOURCING' ? '采购专家' : 
           role === 'LOGISTICS' ? '物流专家' : 
           role === 'ANALYST' ? '数据分析师' : role}
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <span style={{ 
          color: status === 'active' ? '#52c41a' : '#d9d9d9'
        }}>
          {status === 'active' ? '活跃' : '禁用'}
        </span>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '最后登录',
      dataIndex: 'lastLogin',
      key: 'lastLogin',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: User) => (
        <div style={{ display: 'flex', gap: 8 }}>
          <Button 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEditUser(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDeleteUser(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              icon={<DeleteOutlined />} 
              size="small" 
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={4}>用户管理</Title>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAddUser}>
          添加用户
        </Button>
      </div>

      <Card>
        <Table 
          columns={columns} 
          dataSource={users} 
          rowKey="id"
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 用户编辑模态框 */}
      <Modal
        title={editingUser ? "编辑用户" : "添加用户"}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            username: '',
            nickname: '',
            email: '',
            phone: '',
            role: 'OPERATOR',
          }}
        >
          <Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input placeholder="输入用户名" />
          </Item>
          <Item label="昵称" name="nickname" rules={[{ required: true, message: '请输入昵称' }]}>
            <Input placeholder="输入昵称" />
          </Item>
          <Item label="邮箱" name="email" rules={[{ required: true, message: '请输入邮箱' }, { type: 'email', message: '请输入正确的邮箱格式' }]}>
            <Input placeholder="输入邮箱" />
          </Item>
          <Item label="手机号" name="phone" rules={[{ required: true, message: '请输入手机号' }]}>
            <Input placeholder="输入手机号" />
          </Item>
          <Item label="角色" name="role" rules={[{ required: true, message: '请选择角色' }]}>
            <Select>
              <Option value="ADMIN">管理员</Option>
              <Option value="MANAGER">运营主管</Option>
              <Option value="OPERATOR">运营专员</Option>
              <Option value="FINANCE">财务主管</Option>
              <Option value="SOURCING">采购专家</Option>
              <Option value="LOGISTICS">物流专家</Option>
              <Option value="ANALYST">数据分析师</Option>
            </Select>
          </Item>
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12, marginTop: 24 }}>
            <Button onClick={() => setIsModalVisible(false)}>取消</Button>
            <Button type="primary" onClick={handleSaveUser}>
              保存
            </Button>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;