import React, { useState, useEffect } from 'react';
import apiClient from '../utils/request';
import { Card, Button, Table, Tag, Space, Modal, Form, Input, Select, message, Row, Col, Avatar, Popconfirm } from 'antd';
import { PlusOutlined, UserOutlined, LockOutlined, EditOutlined, DeleteOutlined, ReloadOutlined, KeyOutlined } from '@ant-design/icons';

interface User {
  id: number;
  username: string;
  name: string;
  email?: string;
  phone?: string;
  role: string;
  is_active?: boolean;
  created_at?: string;
  updated_at?: string;
}

const UsersPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<User[]>([]);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [resetPwdModalVisible, setResetPwdModalVisible] = useState(false);
  const [addForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [resetPwdForm] = Form.useForm();
  const [currentUser, setCurrentUser] = useState<User | null>(null);

  const roles = [
    { value: 'admin', label: '系统管理员' },
    { value: 'finance', label: '财务专员' },
    { value: 'manager', label: '项目经理' },
    { value: 'employee', label: '普通员工' }
  ];

  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await apiClient.get('/users');
      if (response.data.success) {
        setUsers(response.data.data || []);
      } else {
        message.error('获取用户列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error: any) {
      console.error('获取用户列表失败:', error);
      if (error.response?.status === 403) {
        message.error('权限不足，仅管理员可访问');
      } else {
        message.error('获取用户列表失败');
      }
    } finally {
      setLoading(false);
    }
  };

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

  const handleAdd = async () => {
    try {
      const values = await addForm.validateFields();
      const response = await apiClient.post('/users', values);
      if (response.data.success) {
        message.success('用户已添加');
        setAddModalVisible(false);
        addForm.resetFields();
        fetchUsers();
      } else {
        message.error(response.data.message || '添加失败');
      }
    } catch (error: any) {
      if (error.response?.data?.message) {
        message.error(error.response.data.message);
      } else if (error.errorFields) {
        return;
      } else {
        message.error('添加失败，请重试');
      }
    }
  };

  const handleEdit = (user: User) => {
    setCurrentUser(user);
    editForm.setFieldsValue({
      name: user.name,
      email: user.email,
      phone: user.phone,
      role: user.role
    });
    setEditModalVisible(true);
  };

  const handleEditSubmit = async () => {
    try {
      const values = await editForm.validateFields();
      if (currentUser) {
        const response = await apiClient.put(`/users/${currentUser.id}`, values);
        if (response.data.success) {
          message.success('用户已更新');
          setEditModalVisible(false);
          editForm.resetFields();
          setCurrentUser(null);
          fetchUsers();
        } else {
          message.error(response.data.message || '更新失败');
        }
      }
    } catch (error: any) {
      if (error.response?.data?.message) {
        message.error(error.response.data.message);
      } else if (error.errorFields) {
        return;
      } else {
        message.error('更新失败，请重试');
      }
    }
  };

  const handleResetPassword = (user: User) => {
    setCurrentUser(user);
    resetPwdForm.resetFields();
    setResetPwdModalVisible(true);
  };

  const handleResetPasswordSubmit = async () => {
    try {
      const values = await resetPwdForm.validateFields();
      if (currentUser) {
        const response = await apiClient.put(`/users/${currentUser.id}`, {
          name: currentUser.name,
          email: currentUser.email,
          phone: currentUser.phone,
          role: currentUser.role,
          password: values.newPassword
        });
        if (response.data.success) {
          message.success('密码已重置');
          setResetPwdModalVisible(false);
          resetPwdForm.resetFields();
          setCurrentUser(null);
        } else {
          message.error(response.data.message || '重置失败');
        }
      }
    } catch (error: any) {
      if (error.response?.data?.message) {
        message.error(error.response.data.message);
      } else if (error.errorFields) {
        return;
      } else {
        message.error('重置失败，请重试');
      }
    }
  };

  const handleDelete = async (user: User) => {
    try {
      const response = await apiClient.delete(`/users/${user.id}`);
      if (response.data.success) {
        message.success('用户已删除');
        fetchUsers();
      } else {
        message.error(response.data.message || '删除失败');
      }
    } catch (error: any) {
      if (error.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error('删除失败，请重试');
      }
    }
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 60 },
    { 
      title: '头像', 
      key: 'avatar', 
      width: 60,
      render: () => <Avatar icon={<UserOutlined />} />
    },
    { title: '用户名', dataIndex: 'username', key: 'username', width: 120 },
    { title: '姓名', dataIndex: 'name', key: 'name', width: 120 },
    { title: '邮箱', dataIndex: 'email', key: 'email', width: 180, render: (v: string) => v || '-' },
    { title: '手机号', dataIndex: 'phone', key: 'phone', width: 130, render: (v: string) => v || '-' },
    { 
      title: '角色', 
      dataIndex: 'role', 
      key: 'role', 
      width: 120,
      render: (v: string) => {
        const colors: Record<string, string> = { 'admin': 'red', 'manager': 'blue', 'finance': 'orange', 'employee': 'green' };
        const roleMap = roles.find(role => role.value === v);
        return <Tag color={colors[v] || 'green'}>{roleMap?.label || v || '用户'}</Tag>;
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 240,
      render: (_: any, record: User) => (
        <Space>
          <Button size="small" type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button size="small" type="link" icon={<KeyOutlined />} onClick={() => handleResetPassword(record)}>
            重置密码
          </Button>
          <Popconfirm
            title="确认删除"
            description={`确定要删除用户 ${record.username} 吗？`}
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button size="small" type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h2>用户管理</h2>
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setAddModalVisible(true)}>
            新增用户
          </Button>
          <Button icon={<ReloadOutlined />} onClick={fetchUsers}>刷新</Button>
        </Space>
      </div>

      <Card>
        <Table 
          columns={columns} 
          dataSource={users.map(user => ({ ...user, key: user.id }))} 
          loading={loading} 
          pagination={{ pageSize: 10 }} 
          scroll={{ x: 1000 }} 
        />
      </Card>

      <Modal
        title="新增用户"
        open={addModalVisible}
        onCancel={() => { setAddModalVisible(false); addForm.resetFields(); }}
        onOk={handleAdd}
        width={600}
      >
        <Form form={addForm} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
                <Input placeholder="请输入用户名" prefix={<UserOutlined />} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="姓名" name="name" rules={[{ required: true, message: '请输入姓名' }]}>
                <Input placeholder="请输入姓名" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="邮箱" name="email">
                <Input placeholder="email@example.com" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="手机号" name="phone">
                <Input placeholder="+856 20 xxxx xxxx" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="角色" name="role" rules={[{ required: true, message: '请选择角色' }]} initialValue="employee">
                <Select placeholder="选择角色" options={roles} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="初始密码" name="password" rules={[{ required: true, message: '请输入初始密码' }, { min: 6, message: '密码至少6位' }]}>
                <Input.Password placeholder="请输入初始密码" prefix={<LockOutlined />} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      <Modal
        title="编辑用户"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          setCurrentUser(null);
          editForm.resetFields();
        }}
        onOk={handleEditSubmit}
        width={600}
      >
        <Form form={editForm} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="用户名">
                <Input value={currentUser?.username} disabled prefix={<UserOutlined />} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="姓名" name="name" rules={[{ required: true, message: '请输入姓名' }]}>
                <Input placeholder="请输入姓名" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="邮箱" name="email">
                <Input placeholder="email@example.com" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="手机号" name="phone">
                <Input placeholder="+856 20 xxxx xxxx" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="角色" name="role" rules={[{ required: true, message: '请选择角色' }]}>
                <Select placeholder="选择角色" options={roles} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      <Modal
        title={`重置密码 - ${currentUser?.username || ''}`}
        open={resetPwdModalVisible}
        onCancel={() => {
          setResetPwdModalVisible(false);
          setCurrentUser(null);
          resetPwdForm.resetFields();
        }}
        onOk={handleResetPasswordSubmit}
        width={400}
      >
        <Form form={resetPwdForm} layout="vertical">
          <Form.Item label="新密码" name="newPassword" rules={[{ required: true, message: '请输入新密码' }, { min: 6, message: '密码至少6位' }]}>
            <Input.Password placeholder="请输入新密码" prefix={<LockOutlined />} />
          </Form.Item>
          <Form.Item label="确认密码" name="confirmPassword" rules={[
            { required: true, message: '请确认密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPassword') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入的密码不一致'));
              },
            }),
          ]}>
            <Input.Password placeholder="请再次输入新密码" prefix={<LockOutlined />} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UsersPage;
