import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { useTranslation } from 'react-i18next';
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 { t } = useTranslation();
  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' ? t('mailTemplate.create') : t('mailTemplate.edit'));
    setFormType(type as 'create' | 'update');
    form.resetFields();

    // 修改时，拉取详情并回显
    if (id) {
      setFormLoading(true);
      try {
        const data = await emailTemplateApi.getMailTemplate(id);
        if (!data) {
          message.error(t('mailTemplate.detailFailed'));
          return;
        }
        const status = data.status != null ? Number(data.status) : 1;
        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,
          remark: data.remark ?? '',
        });
      } catch (error: any) {
        message.error(error?.message || t('mailTemplate.detailFailed'));
      } 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(t('mailTemplate.createSuccess') || '邮件模板创建成功');
        } else {
          await emailTemplateApi.updateMailTemplate(data);
          message.success(t('mailTemplate.updateSuccess') || '邮件模板更新成功');
        }
        setDialogVisible(false);
        onSuccess?.();
      } catch (error: any) {
        message.error(error.message || t('common.operationFailed'));
      } finally {
        setFormLoading(false);
      }
    } catch (error) {
      // 表单验证失败
    }
  };

  return (
    <Modal
      title={dialogTitle}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      onOk={submitForm}
      okText={t('common.save')}
      cancelText={t('common.cancel')}
      confirmLoading={formLoading}
      width={1000}
      destroyOnClose
      style={{ top: 20 }}
    >
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        initialValues={{
          status: 1,
        }}
      >
        <Form.Item name="id" hidden>
          <Input type="hidden" />
        </Form.Item>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label={t('mailTemplate.name')}
              name="name"
              rules={[{ required: true, message: t('mailTemplate.nameRequired') }]}
            >
              <Input placeholder={t('mailTemplate.namePlaceholder')} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label={t('mailTemplate.code')}
              name="code"
              rules={[{ required: true, message: t('mailTemplate.codeRequired') }]}
            >
              <Input placeholder={t('mailTemplate.codePlaceholder')} />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label={t('mailTemplate.accountId')}
              name="accountId"
              rules={[{ required: true, message: t('mailTemplate.accountIdRequired') }]}
            >
              <InputNumber placeholder={t('mailTemplate.accountIdPlaceholder')} style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label={t('mailTemplate.nickname')} name="nickname">
              <Input placeholder={t('mailTemplate.nicknamePlaceholder')} />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item label={t('mailTemplate.title')} name="title">
              <Input placeholder={t('common.pleaseEnter')} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label={t('mailTemplate.status')} name="status">
              <Select placeholder={t('mailTemplate.statusPlaceholder')}>
                <Select.Option value={1}>{t('mailTemplate.enable')}</Select.Option>
                <Select.Option value={0}>{t('mailTemplate.disable')}</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          label={t('mailTemplate.content')}
          name="content"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
        >
          <TextArea rows={6} placeholder={t('mailTemplate.contentPlaceholder')} />
        </Form.Item>

        <Form.Item
          label={t('mailTemplate.params')}
          name="params"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
        >
          <Input placeholder={t('mailTemplate.paramsPlaceholder')} />
        </Form.Item>

        <Form.Item
          label={t('mailTemplate.remark')}
          name="remark"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
        >
          <TextArea rows={3} placeholder={t('common.pleaseEnter')} />
        </Form.Item>
      </Form>
    </Modal>
  );
});

MailTemplateForm.displayName = 'MailTemplateForm';

export default MailTemplateForm;

