import React, { useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { dictTypeApi, DictTypeVO } from '../api/DictType';
import { dictDataApi } from '../api/DictData';
import { toast } from 'sonner';
import { Modal, Form, Input, Button, Radio, Spin } from 'antd';
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();
  const [statusOptions, setStatusOptions] = useState<Array<{ label: string; value: number }>>([]);

  // 加载字典管理的状态选项（从接口获取，0=开启，1=关闭）
  useEffect(() => {
    const loadDictStatusOptions = async () => {
      try {
        // 从接口获取 common_status 字典数据
        const response = await dictDataApi.getDictDataPage({
          pageNo: 1,
          pageSize: -1,
          dictType: 'common_status',
        });
        
        const data = (response as any)?.data || response;
        const dictList = data?.list || [];
        
        if (Array.isArray(dictList) && dictList.length > 0) {
          // 使用接口返回的字典数据
          const options = dictList.map((item: any) => ({
            label: item.label,
            value: typeof item.value === 'string' ? parseInt(item.value, 10) : Number(item.value),
          }));
          setStatusOptions(options);
          console.log('DictTypeForm: 从接口获取状态选项', options);
        } else {
          // 如果接口没有数据，使用字典管理的默认定义：0=开启，1=关闭
          setStatusOptions([
            { label: '开启', value: 0 },
            { label: '关闭', value: 1 },
          ]);
        }
      } catch (error) {
        console.error('加载状态选项失败:', error);
        // 使用字典管理的默认定义：0=开启，1=关闭
        setStatusOptions([
          { label: '开启', value: 0 },
          { label: '关闭', value: 1 },
        ]);
      }
    };

    loadDictStatusOptions();
  }, []);

  // 暴露方法给父组件
  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: 0, // 字典管理默认：0=开启
          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;
      // 直接使用接口返回的 status 值，不进行转换
      // 字典管理接口：0=开启，1=关闭
      form.setFieldsValue({
        name: data.name,
        type: data.type,
        status: typeof data.status === 'string' ? parseInt(data.status, 10) : (data.status !== undefined && data.status !== null ? Number(data.status) : 0),
        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);
    }
  };


  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: 0, // 字典管理默认：0=开启
            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;

