import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { Modal, Form, Input, Select, message } from 'antd';
import { userPermissionApi } from '../../api/user/permission';
import { systemApi } from '../../api/System';
import { UserVO, RoleVO } from '../../types';
import { useTranslation } from 'react-i18next';

interface UserAssignRoleFormProps {
  onSuccess?: () => void;
}

export interface UserAssignRoleFormRef {
  open: (row: UserVO) => void;
}

const UserAssignRoleForm = forwardRef<UserAssignRoleFormRef, UserAssignRoleFormProps>(({ onSuccess }, ref) => {
  const { t } = useTranslation();
  const [dialogVisible, setDialogVisible] = useState(false);
  const [formLoading, setFormLoading] = useState(false);
  const [form] = Form.useForm();
  const [roleList, setRoleList] = useState<RoleVO[]>([]);
  const [userId, setUserId] = useState<number | null>(null);

  // 打开弹窗
  const open = async (row: UserVO) => {
    setDialogVisible(true);
    setUserId(row.id);
    form.resetFields();

    // 设置用户信息
    form.setFieldsValue({
      username: row.username,
      nickname: row.nickname,
      roleIds: [],
    });

    // 加载角色列表
    try {
      const roles = await systemApi.getSimpleRoleList();
      setRoleList(roles || []);
    } catch (error) {
      console.error('加载角色列表失败:', error);
      message.error(t('common.loadRoleListFailed'));
    }

    // 获取用户角色列表
    setFormLoading(true);
    try {
      const roleIds = await userPermissionApi.getUserRoleList(row.id);
      form.setFieldsValue({
        roleIds: roleIds || [],
      });
    } catch (error: any) {
      console.error('获取用户角色失败:', error);
      message.error(error.message || t('common.getUserRoleFailed'));
    } finally {
      setFormLoading(false);
    }
  };

  useImperativeHandle(ref, () => ({
    open,
  }));

  // 提交表单
  const submitForm = async () => {
    try {
      const values = await form.validateFields();
      
      setFormLoading(true);
      try {
        const params = {
          userId: userId!,
          roleIds: values.roleIds || [],
        };
        console.log('分配角色参数:', params);
        await userPermissionApi.assignUserRole(params);
        message.success(t('common.assignSuccess'));
        setDialogVisible(false);
        onSuccess?.();
      } catch (error: any) {
        message.error(error.message || t('common.assignFailed'));
      } finally {
        setFormLoading(false);
      }
    } catch (error) {
      // 表单验证失败
    }
  };

  return (
    <Modal
      title={t('common.assignRoleTitle')}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      onOk={submitForm}
      confirmLoading={formLoading}
      okText={t('common.confirm')}
      cancelText={t('common.cancel')}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          roleIds: [],
        }}
      >
        <Form.Item label={t('common.userName')} name="username">
          <Input disabled />
        </Form.Item>

        <Form.Item label={t('common.nickname')} name="nickname">
          <Input disabled />
        </Form.Item>

        <Form.Item label={t('common.assignRole')} name="roleIds">
          <Select
            mode="multiple"
            placeholder={t('common.selectRole')}
            options={roleList.map(role => ({
              label: role.name,
              value: role.id,
            }))}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
});

UserAssignRoleForm.displayName = 'UserAssignRoleForm';

export default UserAssignRoleForm;
