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

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

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

const EmailNotifyForm = forwardRef<EmailNotifyFormRef, EmailNotifyFormProps>(({ 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 [templateList, setTemplateList] = useState<Array<{ label: string; value: string }>>([]);

  // 时间单位配置
  const timeUnits = [
    { name: 'days', label: '天', options: Array.from({ length: 31 }, (_, i) => i) },
    { name: 'hours', label: '小时', options: Array.from({ length: 24 }, (_, i) => i) },
    { name: 'minutes', label: '分钟', options: Array.from({ length: 60 }, (_, i) => i) },
    { name: 'seconds', label: '秒', options: Array.from({ length: 60 }, (_, i) => i) },
  ];

  const [timeValues, setTimeValues] = useState({
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0,
  });

  // 打开弹窗
  const open = async (type: string, id?: number) => {
    setDialogVisible(true);
    setDialogTitle(type === 'create' ? '新增邮件提醒' : '编辑邮件提醒');
    setFormType(type as 'create' | 'update');
    form.resetFields();
    setTimeValues({ days: 0, hours: 0, minutes: 0, seconds: 0 });

    // 加载邮件模板列表
    try {
      const response = await emailTemplateApi.getMailTemplatePage({
        pageNo: 1,
        pageSize: -1,
      });
      setTemplateList(
        response.list.map((item) => ({
          label: item.name,
          value: item.code,
        }))
      );
    } catch (error) {
      console.error('加载邮件模板列表失败:', error);
      setTemplateList([]);
    }

    // 修改时，设置数据
    if (id) {
      setFormLoading(true);
      try {
        const data = await mailNotifyConfigApi.getIsMailNotifyConfigById(id);
        form.setFieldsValue({
          configId: data.configId,
          name: data.name || data.configName,
          templateCode: data.templateCode,
          status: data.status || '1',
        });

        // 转换时间
        const totalSeconds = data.reminderTime || 0;
        setTimeValues({
          days: Math.floor(totalSeconds / (24 * 60 * 60)),
          hours: Math.floor((totalSeconds % (24 * 60 * 60)) / (60 * 60)),
          minutes: Math.floor((totalSeconds % (60 * 60)) / 60),
          seconds: totalSeconds % 60,
        });
      } 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 totalSeconds =
          ((timeValues.days * 24 + timeValues.hours) * 60 + timeValues.minutes) * 60 + timeValues.seconds;

        const data: MailNotifyConfigVO = {
          ...values,
          reminderTime: totalSeconds,
        };

        if (formType === 'create') {
          await mailNotifyConfigApi.addIsMailNotifyConfig(data);
          message.success('创建成功');
        } else {
          await mailNotifyConfigApi.updateIsMailNotifyConfig(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}
      destroyOnHidden
    >
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        initialValues={{
          status: '1',
        }}
      >
        <Form.Item
          label="提醒事项"
          name="name"
          rules={[{ required: true, message: '提醒事项不能为空' }]}
        >
          <Input placeholder="请输入提醒事项" />
        </Form.Item>

        <Form.Item
          label="邮件模板"
          name="templateCode"
          rules={[{ required: true, message: '邮件模板不能为空' }]}
        >
          <Select placeholder="请选择邮件模板" options={templateList} />
        </Form.Item>

        <Form.Item label="提醒时长" required>
          <Row gutter={[16, 0]}>
            {timeUnits.map((unit, index) => (
              <Col key={index} span={6}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <Select
                    value={timeValues[unit.name as keyof typeof timeValues]}
                    onChange={(value) => {
                      setTimeValues((prev) => ({
                        ...prev,
                        [unit.name]: value,
                      }));
                    }}
                    style={{ width: '100%', minWidth: 100 }}
                  >
                    {unit.options.map((option) => (
                      <Select.Option key={option} value={option}>
                        {option}
                      </Select.Option>
                    ))}
                  </Select>
                  <span style={{ fontSize: '14px', color: '#333', whiteSpace: 'nowrap' }}>{unit.label}</span>
                </div>
              </Col>
            ))}
          </Row>
        </Form.Item>
      </Form>
    </Modal>
  );
});

EmailNotifyForm.displayName = 'EmailNotifyForm';

export default EmailNotifyForm;

