import React, { useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { dictDataApi, DictDataVO } from '../api/DictData';
import { toast } from 'sonner';
import { Modal, Form, Input, Button, InputNumber, Radio, Select, Spin } from 'antd';
import { useTranslation } from 'react-i18next';

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

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

const DictDataForm = forwardRef<DictDataFormRef, DictDataFormProps>(({ 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 [currentDictType, setCurrentDictType] = useState<string>('');
  const [form] = Form.useForm();
  const [statusOptions, setStatusOptions] = useState<Array<{ label: string; value: number }>>([]);

  // 颜色类型选项
  const colorTypeOptions = [
    { label: t('form.colorTypeSuccess'), value: 'success' },
    { label: t('form.colorTypeInfo'), value: 'info' },
    { label: t('form.colorTypeWarning'), value: 'warning' },
    { label: t('form.colorTypeDanger'), value: 'danger' },
    { label: t('form.colorTypePrimary'), value: 'primary' },
    { label: t('form.colorTypeDefault'), value: 'default' },
  ];

  // 加载字典管理的状态选项（从接口获取，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) {
          // 使用接口返回的字典数据，不依赖 COMMON_STATUS 的默认定义
          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('DictDataForm: 从接口获取状态选项', 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, dictType?: string) => {
      setDialogTitle(type === 'create' ? t('form.addDictData') : t('form.editDictData'));
      setFormType(type as 'create' | 'update');
      setCurrentId(id);
      setCurrentDictType(dictType || '');
      form.resetFields();

      if (id) {
        loadDictDataData(id);
      } else {
        form.setFieldsValue({
          dictType: dictType || '',
          label: '',
          value: '',
          sort: 0,
          status: 0, // 字典管理默认：0=开启
          colorType: 'default',
          cssClass: '',
          remark: '',
        });
        setFormLoading(false);
      }

      setDialogVisible(true);
    },
  }));

  // 加载字典数据
  const loadDictDataData = async (id: number) => {
    setFormLoading(true);
    try {
      const res = await dictDataApi.getDictData(id);
      const data = (res as any)?.data || res;
      setCurrentDictType(data.dictType || '');
      // 直接使用接口返回的 status 值，不进行转换
      // 字典管理接口：0=开启，1=关闭
      form.setFieldsValue({
        dictType: data.dictType || '',
        label: data.label || '',
        value: data.value || '',
        sort: data.sort ?? 0,
        status: typeof data.status === 'string' ? parseInt(data.status, 10) : (data.status !== undefined && data.status !== null ? Number(data.status) : 0),
        colorType: data.colorType || 'default',
        cssClass: data.cssClass || '',
        remark: data.remark || '',
      });
    } catch (error: any) {
      toast.error(error.message || t('form.getDictDataDetailFailed'));
    } finally {
      setFormLoading(false);
    }
  };

  // 提交表单
  const submitForm = async () => {
    try {
      const values = await form.validateFields();
      setFormLoading(true);
      
      const submitData: DictDataVO = {
        ...values,
        sort: Number(values.sort) || 0,
        status: Number(values.status),
        colorType: values.colorType || 'default',
      };

      if (formType === 'create') {
        await dictDataApi.createDictData(submitData);
        toast.success(t('form.createSuccess'));
      } else {
        if (currentId) {
          submitData.id = currentId;
        }
        await dictDataApi.updateDictData(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={800}
      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={{
            sort: 0,
            status: 0, // 字典管理默认：0=开启
            colorType: 'default',
            remark: '',
          }}
        >
          <Form.Item
            label={t('form.dictType')}
            name="dictType"
            labelStyle={{ whiteSpace: 'nowrap' }}
            rules={[{ required: true, message: t('form.dictTypeRequired') }]}
          >
            <Input 
              placeholder={t('form.dictTypePlaceholder')} 
              disabled={formType === 'update'}
            />
          </Form.Item>

          <Form.Item
            label={t('form.dataLabel')}
            name="label"
            labelStyle={{ whiteSpace: 'nowrap' }}
            rules={[
              { required: true, message: t('form.dataLabelRequired') },
              { max: 50, message: t('form.dataLabelMaxLength') },
            ]}
          >
            <Input placeholder={t('form.dataLabelPlaceholder')} />
          </Form.Item>

          <Form.Item
            label={t('form.dataValue')}
            name="value"
            labelStyle={{ whiteSpace: 'nowrap' }}
            rules={[
              { required: true, message: t('form.dataValueRequired') },
              { max: 50, message: t('form.dataValueMaxLength') },
            ]}
          >
            <Input placeholder={t('form.dataValuePlaceholder')} />
          </Form.Item>

          <Form.Item
            label={t('form.displaySort')}
            name="sort"
            labelStyle={{ whiteSpace: 'nowrap' }}
            rules={[{ required: true, message: t('form.displaySortRequired') }]}
          >
            <InputNumber 
              placeholder={t('form.displaySortPlaceholder')} 
              min={0} 
              style={{ width: '100%' }}
            />
          </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('table.colorType')}
            name="colorType"
            labelStyle={{ whiteSpace: 'nowrap' }}
          >
            <Select placeholder={t('form.colorTypePlaceholder')}>
              {colorTypeOptions.map((option) => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label} ({option.value})
                </Select.Option>
              ))}
            </Select>
          </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>
  );
});

DictDataForm.displayName = 'DictDataForm';

export default DictDataForm;

