import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Modal, Form, Input, message } from 'antd';
import { emailTemplateApi, MailSendReqVO } from '../../api/emailTemplate';

const { TextArea } = Input;

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

export interface MailTemplateSendFormRef {
  open: (id: number) => void;
}

const MailTemplateSendForm = forwardRef<MailTemplateSendFormRef, MailTemplateSendFormProps>(({ onSuccess }, ref) => {
  const { t } = useTranslation();
  const [dialogVisible, setDialogVisible] = useState(false);
  const [formLoading, setFormLoading] = useState(false);
  const [form] = Form.useForm();
  const [templateContent, setTemplateContent] = useState('');
  const [templateParams, setTemplateParams] = useState<string[]>([]);
  const [templateCode, setTemplateCode] = useState('');

  // 打开弹窗
  const open = async (id: number) => {
    setDialogVisible(true);
    form.resetFields();
    setTemplateContent('');
    setTemplateParams([]);
    setTemplateCode('');

    setFormLoading(true);
    try {
      const data = await emailTemplateApi.getMailTemplate(id);
      setTemplateContent(data.content || '');
      setTemplateCode(data.code || '');
      
      // 解析参数（params 可能为字符串或数组）
      if (data.params != null && data.params !== '') {
        const raw = data.params;
        const paramsArray = Array.isArray(raw)
          ? raw.map((p: any) => String(p).trim()).filter((p: string) => p)
          : String(raw).split(',').map((p: string) => p.trim()).filter((p: string) => p);
        setTemplateParams(paramsArray);
        
        // 初始化表单参数值
        const initialValues: Record<string, string> = {
          mail: '',
          templateCode: data.code,
        };
        paramsArray.forEach((param: string) => {
          initialValues[`templateParams.${param}`] = '';
        });
        form.setFieldsValue(initialValues);
      }
    } catch (error: any) {
      message.error(error.message || '获取邮件模板详情失败');
    } finally {
      setFormLoading(false);
    }
  };

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

  // 提交表单
  const submitForm = async () => {
    try {
      const values = await form.validateFields();

      setFormLoading(true);
      try {
        // 构建模板参数对象
        const params: Record<string, any> = {};
        templateParams.forEach((param) => {
          const value = values[`templateParams.${param}`];
          if (value !== undefined && value !== null) {
            params[param] = value;
          }
        });

        const data: MailSendReqVO = {
          mail: values.mail,
          templateCode: templateCode,
          templateParams: params,
        };

        const logId = await emailTemplateApi.sendMail(data);
        if (logId) {
          message.success(`提交发送成功！发送结果，见发送日志编号：${logId}`);
        } else {
          message.success('提交发送成功！');
        }
        setDialogVisible(false);
        onSuccess?.();
      } catch (error: any) {
        message.error(error.message || '发送失败');
      } finally {
        setFormLoading(false);
      }
    } catch (error) {
      // 表单验证失败
    }
  };

  return (
    <Modal
      title={t('mailTemplate.test')}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      onOk={submitForm}
      okText={t('common.save')}
      cancelText={t('common.cancel')}
      confirmLoading={formLoading}
      width={600}
      destroyOnClose
    >
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <Form.Item label="模板内容">
          <TextArea
            value={templateContent}
            rows={6}
            readOnly
            style={{ backgroundColor: '#f5f5f5' }}
          />
        </Form.Item>

        <Form.Item
          label="收件邮箱"
          name="mail"
          rules={[{ required: true, message: '邮箱不能为空' }, { type: 'email', message: '请输入正确的邮箱地址' }]}
        >
          <Input placeholder="请输入收件邮箱" />
        </Form.Item>

        {templateParams.map((param) => (
          <Form.Item
            key={param}
            label={`参数 {${param}}`}
            name={`templateParams.${param}`}
            rules={[{ required: true, message: `参数 ${param} 不能为空` }]}
          >
            <Input placeholder={`请输入 ${param} 参数`} />
          </Form.Item>
        ))}
      </Form>
    </Modal>
  );
});

MailTemplateSendForm.displayName = 'MailTemplateSendForm';

export default MailTemplateSendForm;

