import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { roleApi, RoleVO } from '../api/Role';
import { toast } from 'sonner';
import { Modal, Form, Input, Button, Select, Spin } from 'antd';
import { CommonStatusEnum } from '../utils/constants';
import { getIntDictOptions, DICT_TYPE } from '../utils/dict';
import { useTranslation } from 'react-i18next';

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

export interface RoleFormRef {
  open: (type: string, id?: number) => void;
}

const RoleForm = forwardRef<RoleFormRef, RoleFormProps>(({ onSuccess }, ref) => {
  const { t } = useTranslation();
  const [dialogVisible, setDialogVisible] = useState(false);
  const [dialogTitle, setDialogTitle] = useState('');
  const [formType, setFormType] = useState<'create' | 'update'>('create');
  const [formLoading, setFormLoading] = useState(false);
  const [currentId, setCurrentId] = useState<number | undefined>();
  const [form] = Form.useForm();
  
  // 获取最新的字典选项（每次调用都从缓存中获取最新数据）
  const getStatusOptions = () => getIntDictOptions(DICT_TYPE.COMMON_STATUS);

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    open: (type: string, id?: number) => {
      setDialogTitle(type === 'create' ? t('role.addRole') : t('role.editRole'));
      setFormType(type as 'create' | 'update');
      setCurrentId(id);
      form.resetFields();

      if (id) {
        loadRoleData(id);
      } else {
        // 从字典中获取默认启用状态值
        const defaultStatus = getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1;
        form.setFieldsValue({
          name: '',
          code: '',
          sort: 0,
          status: defaultStatus,
          remark: '',
        });
        setFormLoading(false);
      }

      setDialogVisible(true);
    },
  }));

  // 加载角色数据
  const loadRoleData = async (id: number) => {
    setFormLoading(true);
    try {
      const res = await roleApi.getRole(id);
      const data = (res as any)?.data || res;
      form.setFieldsValue({
        name: data.name,
        code: data.code,
        sort: data.sort ?? 0,
        status: typeof data.status === 'string' ? Number(data.status) : (data.status ?? (getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1)),
        remark: data.remark || '',
      });
    } catch (error: any) {
      toast.error(error.message || t('role.getRoleDetailFailed'));
    } finally {
      setFormLoading(false);
    }
  };

  // 提交表单
  const submitForm = async () => {
    try {
      const values = await form.validateFields();
      setFormLoading(true);
      
      const submitData: RoleVO = {
        ...values,
        sort: Number(values.sort) || 0,
        status: Number(values.status),
        type: 1, // 默认类型，可根据实际需求调整
        dataScope: 1, // 默认数据权限，可根据实际需求调整
      };

      if (formType === 'create') {
        await roleApi.createRole(submitData);
        toast.success(t('role.createSuccess'));
      } else {
        if (currentId) {
          submitData.id = currentId;
        }
        await roleApi.updateRole(submitData);
        toast.success(t('role.updateSuccess'));
      }
      setDialogVisible(false);
      onSuccess?.();
    } catch (error: any) {
      if (error.errorFields) {
        // 表单验证错误
        return;
      }
      toast.error(error.message || t('role.operationFailed'));
    } finally {
      setFormLoading(false);
    }
  };

  return (
    <Modal
      title={dialogTitle}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      onOk={submitForm}
      confirmLoading={formLoading}
      okText={t('common.confirm')}
      cancelText={t('common.cancel')}
      width={700}
      destroyOnClose
    >
      <Spin spinning={formLoading && formType === 'update'}>
        <Form
          form={form}
          layout="horizontal"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          initialValues={{
            sort: 0,
            status: getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1,
            remark: '',
          }}
        >
          <Form.Item
            label={t('role.roleName')}
            name="name"
            rules={[
              { required: true, message: t('role.roleNameRequired') },
              { max: 50, message: t('role.roleNameMaxLength') },
            ]}
          >
            <Input placeholder={t('role.roleNamePlaceholder')} style={{ maxWidth: '400px' }} />
          </Form.Item>

          <Form.Item
            label={t('role.roleCode')}
            name="code"
            rules={[
              { required: true, message: t('role.roleCodeRequired') },
              { max: 50, message: t('role.roleCodeMaxLength') },
            ]}
          >
            <Input placeholder={t('role.roleCodePlaceholder')} style={{ maxWidth: '400px' }} />
          </Form.Item>

          <Form.Item
            label={t('role.displayOrder')}
            name="sort"
            rules={[{ required: true, message: t('role.displayOrderRequired') }]}
          >
            <Input type="number" placeholder={t('role.displayOrderPlaceholder')} min={0} style={{ maxWidth: '400px' }} />
          </Form.Item>

          <Form.Item
            label={t('role.status')}
            name="status"
            rules={[{ required: true, message: t('role.statusRequired') }]}
          >
            <Select placeholder={t('role.statusPlaceholder')} style={{ maxWidth: '400px' }}>
              {getStatusOptions().map((option) => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label={t('role.remark')}
            name="remark"
          >
            <Input.TextArea placeholder={t('role.remarkPlaceholder')} rows={4} style={{ maxWidth: '400px' }} />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
});

RoleForm.displayName = 'RoleForm';

export default RoleForm;

