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';
import { useTranslation } from 'react-i18next';

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

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

// 提醒时长下拉选项：天 0-30，时 0-23，分 0-59，秒 0-59
const DURATION_DAYS_OPTIONS = Array.from({ length: 31 }, (_, i) => i);
const DURATION_HOURS_OPTIONS = Array.from({ length: 24 }, (_, i) => i);
const DURATION_MINUTES_OPTIONS = Array.from({ length: 60 }, (_, i) => i);
const DURATION_SECONDS_OPTIONS = Array.from({ length: 60 }, (_, i) => i);

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

  const timeUnits = [
    { name: 'days', label: t('common.day'), options: DURATION_DAYS_OPTIONS },
    { name: 'hours', label: t('common.hour'), options: DURATION_HOURS_OPTIONS },
    { name: 'minutes', label: t('common.minute'), options: DURATION_MINUTES_OPTIONS },
    { name: 'seconds', label: t('common.second'), options: DURATION_SECONDS_OPTIONS },
  ];

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

  // 打开弹窗
  const open = async (type: string, id?: number) => {
    setDialogVisible(true);
    setDialogTitle(type === 'create' ? t('notificationManagement.addEmailNotify') : t('notificationManagement.editEmailNotify'));
    setFormType(type as 'create' | 'update');
    form.resetFields();
    setTimeValues({ days: 0, hours: 0, minutes: 0, seconds: 0 });

    // 先加载邮件模板列表（编辑时回显模板依赖该列表）
    let templates: Array<{ label: string; value: string }> = [];
    try {
      const response = await emailTemplateApi.getMailTemplatePage({
        pageNo: 1,
        pageSize: -1,
      });
      templates = (response.list || []).map((item) => ({
        label: item.name,
        value: item.code,
      }));
      setTemplateList(templates);
    } catch (error) {
      console.error(t('mailTemplate.fetchListFailed'), error);
      setTemplateList([]);
    }

    // 修改时，拉取详情并回显（调用 iscs/mail-notify-config/selectMailNotifyConfigById?id=xxx）
    if (type === 'update' && (id == null || id === undefined)) {
      message.warning(t('notificationManagement.getEmailListFailed') || '缺少记录 ID，无法加载详情');
      return;
    }
    if (id) {
      setFormLoading(true);
      try {
        const data = await mailNotifyConfigApi.getIsMailNotifyConfigById(id);
        if (!data) {
          message.error(t('notificationManagement.getEmailListFailed'));
          return;
        }
        const recordId = (data as any).id ?? data.configId;
        const name = data.name ?? data.configName ?? '';
        let templateCode = data.templateCode ?? (data as any).templateCode ?? '';
        if (!templateCode && (data as any).templateName && templates.length > 0) {
          const byName = templates.find((t) => t.label === (data as any).templateName);
          if (byName) templateCode = byName.value;
        }
        const status = data.status != null ? String(data.status) : '1';

        form.setFieldsValue({
          id: recordId,
          name,
          templateCode,
          status,
        });

        const totalSeconds = Number(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 || t('notificationManagement.getEmailListFailed'));
      } 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(t('notificationManagement.addEmailNotifySuccess') || '邮件提醒新增成功');
        } else {
          await mailNotifyConfigApi.updateIsMailNotifyConfig(data);
          message.success(t('notificationManagement.updateEmailNotifySuccess') || '邮件提醒保存成功');
        }
        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={800}
      destroyOnHidden
    >
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        initialValues={{
          status: '1',
        }}
      >
        <Form.Item name="id" hidden>
          <Input type="hidden" />
        </Form.Item>
        <Form.Item
          label={t('notificationManagement.reminderItem')}
          name="name"
          rules={[{ required: true, message: t('notificationManagement.reminderItemRequired') }]}
        >
          <Input placeholder={t('notificationManagement.placeholderReminderItem')} />
        </Form.Item>

        <Form.Item
          label={t('notificationManagement.setMailTemplate')}
          name="templateCode"
          rules={[{ required: true, message: t('notificationManagement.mailTemplateRequired') }]}
        >
          <Select placeholder={t('common.pleaseSelect')} options={templateList} />
        </Form.Item>

        <Form.Item label={t('notificationManagement.reminderDuration')} 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;

