import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { Modal, Form, Input, InputNumber, Select, Row, Col, message } from 'antd';
import { emailTemplateApi, MailTemplateVO } from '../../api/emailTemplate';

const { TextArea } = Input;

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

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

const MailTemplateForm = forwardRef<MailTemplateFormRef, MailTemplateFormProps>(({ onSuccess }, ref) => {
  const [dialogVisible, setDialogVisible] = useState(false);
  const [dialogTitle, setDialogTitle] = useState('');
  const [formLoading, setFormLoading] = useState(false);
  const [formType, setFormType] = useState<'create' | 'update'>('create');
  const [form] = Form.useForm();

  // 打开弹窗
  const open = async (type: string, id?: number) => {
    setDialogVisible(true);
    setDialogTitle(type === 'create' ? '新增邮件模板' : '编辑邮件模板');
    setFormType(type as 'create' | 'update');
    form.resetFields();

    // 修改时，设置数据
    if (id) {
      setFormLoading(true);
      try {
        const data = await emailTemplateApi.getMailTemplate(id);
        form.setFieldsValue({
          id: data.id,
          name: data.name,
          code: data.code,
          accountId: data.accountId,
          nickname: data.nickname,
          title: data.title,
          content: data.content,
          params: data.params,
          status: data.status,
          remark: data.remark,
        });
      } catch (error: any) {
        message.error(error.message || '获取邮件模板详情失败');
      } finally {
        setFormLoading(false);
      }
    } else {
      // 新增时设置默认值
      form.setFieldsValue({
        status: 1,
      });
    }
  };

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

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

      setFormLoading(true);
      try {
        const data: MailTemplateVO = {
          ...values,
        };

        if (formType === 'create') {
          await emailTemplateApi.createMailTemplate(data);
          message.success('创建成功');
        } else {
          await emailTemplateApi.updateMailTemplate(data);
          message.success('更新成功');
        }
        setDialogVisible(false);
        onSuccess?.();
      } catch (error: any) {
        message.error(error.message || '操作失败');
      } finally {
        setFormLoading(false);
      }
    } catch (error) {
      // 表单验证失败
    }
  };

  return (
    <Modal
      title={dialogTitle}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      onOk={submitForm}
      confirmLoading={formLoading}
      width={800}
      destroyOnClose
    >
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        initialValues={{
          status: 1,
        }}
      >
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="模板名称"
              name="name"
              rules={[{ required: true, message: '模板名称不能为空' }]}
            >
              <Input placeholder="请输入模板名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="模板编码"
              name="code"
              rules={[{ required: true, message: '模板编码不能为空' }]}
            >
              <Input placeholder="请输入模板编码" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item label="账号ID" name="accountId">
              <InputNumber placeholder="请输入账号ID" style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="昵称" name="nickname">
              <Input placeholder="请输入昵称" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item label="标题" name="title">
              <Input placeholder="请输入标题" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="状态" name="status">
              <Select placeholder="请选择状态">
                <Select.Option value={1}>启用</Select.Option>
                <Select.Option value={0}>禁用</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={24}>
            <Form.Item label="模板内容" name="content">
              <TextArea rows={6} placeholder="请输入模板内容" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={24}>
            <Form.Item label="参数" name="params">
              <Input placeholder="请输入参数，多个参数用逗号分隔，如：name,code" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={24}>
            <Form.Item label="备注" name="remark">
              <TextArea rows={3} placeholder="请输入备注" />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
});

MailTemplateForm.displayName = 'MailTemplateForm';

export default MailTemplateForm;

