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

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

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

const DictTypeForm = forwardRef<DictTypeFormRef, DictTypeFormProps>(({ 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();

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

      if (id) {
        loadDictTypeData(id);
      } else {
        form.setFieldsValue({
          name: '',
          type: '',
          status: CommonStatusEnum.ENABLE,
          remark: '',
        });
        setFormLoading(false);
      }

      setDialogVisible(true);
    },
  }));

  // 加载字典类型数据
  const loadDictTypeData = async (id: number) => {
    setFormLoading(true);
    try {
      const res = await dictTypeApi.getDictType(id);
      const data = (res as any)?.data || res;
      form.setFieldsValue({
        name: data.name,
        type: data.type,
        status: typeof data.status === 'string' ? Number(data.status) : (data.status ?? CommonStatusEnum.ENABLE),
        remark: data.remark || '',
      });
    } catch (error: any) {
      toast.error(error.message || t('form.getDictTypeDetailFailed'));
    } finally {
      setFormLoading(false);
    }
  };

  // 提交表单
  const submitForm = async () => {
    try {
      const values = await form.validateFields();
      setFormLoading(true);
      
      const submitData: DictTypeVO = {
        ...values,
        status: Number(values.status),
      };

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

  const statusOptions = getIntDictOptions(DICT_TYPE.COMMON_STATUS);

  return (
    <Modal
      title={dialogTitle}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      onOk={submitForm}
      confirmLoading={formLoading}
      okText={t('common.confirm')}
      cancelText={t('common.cancel')}
      width={720}
      destroyOnClose
    >
      <Spin spinning={formLoading && formType === 'update'}>
        <Form
          form={form}
          layout="horizontal"
          labelCol={{ flex: '140px', style: { minWidth: '140px', paddingRight: '12px' } }}
          wrapperCol={{ flex: 'auto' }}
          labelAlign="left"
          colon={false}
          initialValues={{
            status: CommonStatusEnum.ENABLE,
            remark: '',
          }}
        >
          <Form.Item
            label={t('form.dictName')}
            name="name"
            labelStyle={{ whiteSpace: 'nowrap' }}
            rules={[
              { required: true, message: t('form.dictNameRequired') },
              { max: 50, message: t('form.dictNameMaxLength') },
            ]}
          >
            <Input placeholder={t('form.dictNamePlaceholder')} />
          </Form.Item>

          <Form.Item
            label={t('form.dictType')}
            name="type"
            labelStyle={{ whiteSpace: 'nowrap' }}
            rules={[
              { required: true, message: t('form.dictTypeRequired') },
              { max: 50, message: t('form.dictTypeMaxLength') },
            ]}
          >
            <Input 
              placeholder={t('form.dictTypePlaceholder')} 
              disabled={formType === 'update'}
            />
          </Form.Item>

          <Form.Item
            label={t('form.status')}
            name="status"
            labelStyle={{ whiteSpace: 'nowrap' }}
            rules={[{ required: true, message: t('form.statusRequired') }]}
          >
            <Radio.Group>
              {statusOptions.map((option) => (
                <Radio key={option.value} value={option.value}>
                  {option.label}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

          <Form.Item
            label={t('form.remark')}
            name="remark"
            labelStyle={{ whiteSpace: 'nowrap' }}
          >
            <Input.TextArea placeholder={t('form.remarkPlaceholder')} rows={4} />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
});

DictTypeForm.displayName = 'DictTypeForm';

export default DictTypeForm;

