import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Select, message, Card, Modal, Form } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { settingsDataSource, User } from '@/services/settingsDataSource';

const { Option } = Select;
const { Search } = Input;

const UserManagement: React.FC = () => {
  const navigate = useNavigate();
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    role: '',
    status: '',
    search: '',
  });
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();

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

  const fetchUsers = async () => {
    setLoading(true);
    try {
      const data = await settingsDataSource.fetchUsers();
      setUsers(data);
    } catch (error) {
      message.error('Failed to load users');
    } finally {
      setLoading(false);
    }
  };

  const handleAddUser = () => {
    setIsModalVisible(true);
  };

  const handleEditUser = (id: string) => {
    message.info('编辑用户功能开发中');
  };

  const handleDeleteUser = (id: string) => {
    message.success('用户已删除');
    fetchUsers();
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      message.success('用户已添加');
      setIsModalVisible(false);
      setLoading(false);
      fetchUsers();
    }, 1000);
  };

  const handleBack = () => {
    navigate('/settings');
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role: string) => {
        const roleMap = {
          ADMIN: '管理员',
          MANAGER: '运营主管',
          OPERATOR: '运营专员',
          FINANCE: '财务主管',
          SOURCING: '采购专家',
          LOGISTICS: '物流专家',
          ANALYST: '数据分析师',
        };
        return roleMap[role] || role;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          active: '活跃',
          inactive: '非活跃',
        };
        return statusMap[status] || status;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '最后登录',
      dataIndex: 'lastLogin',
      key: 'lastLogin',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: User) => (
        <div>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditUser(record.id)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteUser(record.id)}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className="user-management">
      <div className="page-header">
        <h1>用户管理</h1>
        <div style={{ display: 'flex', gap: 16 }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAddUser}
          >
            添加用户
          </Button>
          <Button
            icon={<ArrowLeftOutlined />}
            onClick={handleBack}
          >
            返回
          </Button>
        </div>
      </div>

      <div className="filter-section" style={{ marginBottom: 24, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
        <Search
          placeholder="搜索用户名或邮箱"
          style={{ width: 300 }}
          onChange={(e) => setFilters({ ...filters, search: e.target.value })}
        />
        <Select
          placeholder="角色"
          style={{ width: 120 }}
          onChange={(value) => setFilters({ ...filters, role: value })}
        >
          <Option value="">全部</Option>
          <Option value="ADMIN">管理员</Option>
          <Option value="MANAGER">运营主管</Option>
          <Option value="OPERATOR">运营专员</Option>
          <Option value="FINANCE">财务主管</Option>
        </Select>
        <Select
          placeholder="状态"
          style={{ width: 120 }}
          onChange={(value) => setFilters({ ...filters, status: value })}
        >
          <Option value="">全部</Option>
          <Option value="active">活跃</Option>
          <Option value="inactive">非活跃</Option>
        </Select>
        <Button
          icon={<SearchOutlined />}
          onClick={fetchUsers}
        >
          筛选
        </Button>
      </div>

      <Card title="用户列表">
        <Table
          columns={columns}
          dataSource={users}
          loading={loading}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
          }}
        />
      </Card>

      <Modal
        title="添加用户"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[{ required: true, message: '请输入邮箱' }]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>

          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select placeholder="请选择角色">
              <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>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;