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

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

const RoleManagement: React.FC = () => {
  const [roles, setRoles] = useState<Role[]>([
    {
      id: '1',
      name: '管理员',
      code: 'ADMIN',
      description: '系统管理员，拥有所有权限',
      status: 'active',
      createdAt: '2026-03-01',
      updatedAt: '2026-03-01',
    },
    {
      id: '2',
      name: '运营主管',
      code: 'MANAGER',
      description: '运营主管，拥有运营相关权限',
      status: 'active',
      createdAt: '2026-03-02',
      updatedAt: '2026-03-02',
    },
    {
      id: '3',
      name: '运营专员',
      code: 'OPERATOR',
      description: '运营专员，拥有基础运营权限',
      status: 'active',
      createdAt: '2026-03-03',
      updatedAt: '2026-03-03',
    },
  ]);

  const [permissions, setPermissions] = useState<Permission[]>([
    {
      id: '1',
      name: '商品管理',
      code: 'PRODUCT_MANAGE',
      children: [
        { id: '1-1', name: '商品列表', code: 'PRODUCT_LIST' },
        { id: '1-2', name: '商品添加', code: 'PRODUCT_ADD' },
        { id: '1-3', name: '商品编辑', code: 'PRODUCT_EDIT' },
        { id: '1-4', name: '商品删除', code: 'PRODUCT_DELETE' },
      ],
    },
    {
      id: '2',
      name: '订单管理',
      code: 'ORDER_MANAGE',
      children: [
        { id: '2-1', name: '订单列表', code: 'ORDER_LIST' },
        { id: '2-2', name: '订单详情', code: 'ORDER_DETAIL' },
        { id: '2-3', name: '订单处理', code: 'ORDER_PROCESS' },
      ],
    },
    {
      id: '3',
      name: '用户管理',
      code: 'USER_MANAGE',
      children: [
        { id: '3-1', name: '用户列表', code: 'USER_LIST' },
        { id: '3-2', name: '用户添加', code: 'USER_ADD' },
        { id: '3-3', name: '用户编辑', code: 'USER_EDIT' },
        { id: '3-4', name: '用户删除', code: 'USER_DELETE' },
      ],
    },
    {
      id: '4',
      name: '系统管理',
      code: 'SYSTEM_MANAGE',
      children: [
        { id: '4-1', name: '角色管理', code: 'ROLE_MANAGE' },
        { id: '4-2', name: '权限管理', code: 'PERMISSION_MANAGE' },
        { id: '4-3', name: '系统配置', code: 'SYSTEM_CONFIG' },
      ],
    },
  ]);

  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [isPermissionModalVisible, setIsPermissionModalVisible] = useState<boolean>(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [selectedRole, setSelectedRole] = useState<Role | null>(null);
  const [form] = Form.useForm();

  const handleAddRole = () => {
    setEditingRole(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEditRole = (role: Role) => {
    setEditingRole(role);
    form.setFieldsValue(role);
    setIsModalVisible(true);
  };

  const handleDeleteRole = (id: string) => {
    const updatedRoles = roles.filter(role => role.id !== id);
    setRoles(updatedRoles);
    message.success('角色已删除');
  };

  const handleSaveRole = () => {
    form.validateFields().then(values => {
      if (editingRole) {
        const updatedRoles = roles.map(role => 
          role.id === editingRole.id ? { ...role, ...values, updatedAt: new Date().toISOString().split('T')[0] } : role
        );
        setRoles(updatedRoles);
        message.success('角色信息已更新');
      } else {
        const newRole: Role = {
          id: (roles.length + 1).toString(),
          ...values,
          status: 'active',
          createdAt: new Date().toISOString().split('T')[0],
          updatedAt: new Date().toISOString().split('T')[0],
        };
        setRoles([...roles, newRole]);
        message.success('角色已添加');
      }
      setIsModalVisible(false);
    });
  };

  const handleEditPermissions = (role: Role) => {
    setSelectedRole(role);
    setIsPermissionModalVisible(true);
  };

  const handleSavePermissions = () => {
    message.success('权限配置已保存');
    setIsPermissionModalVisible(false);
  };

  const columns = [
    {
      title: '角色ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '角色编码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      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: 'updatedAt',
      key: 'updatedAt',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Role) => (
        <div style={{ display: 'flex', gap: 8 }}>
          <Button 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEditRole(record)}
          >
            编辑
          </Button>
          <Button 
            icon={<SettingOutlined />} 
            size="small"
            onClick={() => handleEditPermissions(record)}
          >
            权限
          </Button>
          <Popconfirm
            title="确定要删除这个角色吗？"
            onConfirm={() => handleDeleteRole(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={handleAddRole}>
          添加角色
        </Button>
      </div>

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

      {/* 角色编辑模态框 */}
      <Modal
        title={editingRole ? "编辑角色" : "添加角色"}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            name: '',
            code: '',
            description: '',
          }}
        >
          <Item label="角色名称" name="name" rules={[{ required: true, message: '请输入角色名称' }]}>
            <Input placeholder="输入角色名称" />
          </Item>
          <Item label="角色编码" name="code" rules={[{ required: true, message: '请输入角色编码' }]}>
            <Input placeholder="输入角色编码" />
          </Item>
          <Item label="描述" name="description">
            <Input.TextArea placeholder="输入角色描述" />
          </Item>
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12, marginTop: 24 }}>
            <Button onClick={() => setIsModalVisible(false)}>取消</Button>
            <Button type="primary" onClick={handleSaveRole}>
              保存
            </Button>
          </div>
        </Form>
      </Modal>

      {/* 权限配置模态框 */}
      <Modal
        title={`${selectedRole?.name} 权限配置`}
        open={isPermissionModalVisible}
        onCancel={() => setIsPermissionModalVisible(false)}
        onOk={handleSavePermissions}
        width={800}
      >
        <Tree
          checkable
          treeData={permissions}
          defaultExpandAll
        />
      </Modal>
    </div>
  );
};

export default RoleManagement;