import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Tree, message } from 'antd';
import { request } from '@umijs/max';
import type { PermissionItem } from '../types';

interface AddRoleModalProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const AddRoleModal: React.FC<AddRoleModalProps> = ({ visible, onClose, onSuccess }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [permissions, setPermissions] = useState<PermissionItem[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);

  // 获取权限树
  useEffect(() => {
    if (visible) {
      fetchPermissions();
    }
  }, [visible]);

  const fetchPermissions = async () => {
    try {
      const res = await request('/api/admin/role/permissions');
      if (res.code === 0) {
        setPermissions(res.data);
      }
    } catch {
      message.error('获取权限列表失败');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      const res = await request('/api/admin/role/create', {
        method: 'POST',
        data: {
          ...values,
          permissions: checkedKeys,
        },
      });
      
      if (res.code === 0) {
        message.success('创建成功');
        onSuccess();
        handleClose();
      } else {
        message.error(res.message);
      }
    } catch {
      // 表单验证失败
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    form.resetFields();
    setCheckedKeys([]);
    onClose();
  };

  // 转换权限数据为树形结构
  const convertToTreeData = (items: PermissionItem[]) => {
    return items.map(item => ({
      title: item.name,
      key: item.id,
      children: item.children ? convertToTreeData(item.children) : undefined,
    }));
  };

  return (
    <Modal
      title="新增角色"
      open={visible}
      onOk={handleSubmit}
      onCancel={handleClose}
      confirmLoading={loading}
      width={600}
      okText="确定"
      cancelText="取消"
      okButtonProps={{
        style: { background: '#00A196', borderColor: '#00A196' }
      }}
    >
      <Form
        form={form}
        layout="vertical"
        requiredMark={false}
      >
        <Form.Item
          name="name"
          label="角色名称"
          rules={[{ required: true, message: '请输入角色名称' }]}
        >
          <Input placeholder="请输入角色名称" />
        </Form.Item>
        
        <Form.Item
          name="description"
          label="角色描述"
        >
          <Input.TextArea
            placeholder="请输入角色描述"
            rows={3}
          />
        </Form.Item>
        
        <Form.Item
          label="权限配置"
        >
          <Tree
            checkable
            checkedKeys={checkedKeys}
            onCheck={(keys) => setCheckedKeys(keys as string[])}
            treeData={convertToTreeData(permissions)}
            height={300}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddRoleModal;