import { LockOutlined, MailOutlined, SafetyOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import {
  Alert,
  App,
  Button,
  Col,
  Form,
  Input,
  Modal,
  Row,
  Steps,
  Result,
} from 'antd';
import React, { useEffect, useState, useCallback } from 'react';
import { createStyles } from 'antd-style';
import {
  forgotPassword,
  resendForgotPasswordCode,
  resetPassword,
} from '@/services/auth/api';
import { getErrorMessage, extractErrorMessage, getApiLanguage } from '@/services/auth/errorCodes';

const useStyles = createStyles(() => ({
  steps: {
    marginBottom: 24,
  },
  getCaptcha: {
    width: '100%',
  },
}));

interface ForgotPasswordModalProps {
  open: boolean;
  onClose: () => void;
}

type ResetStep = 'email' | 'verify' | 'reset' | 'success';

const ForgotPasswordModal: React.FC<ForgotPasswordModalProps> = ({
  open,
  onClose,
}) => {
  const { styles } = useStyles();
  const intl = useIntl();
  const { message } = App.useApp();

  const [step, setStep] = useState<ResetStep>('email');
  const [email, setEmail] = useState<string>('');
  const [code, setCode] = useState<string>('');
  const [count, setCount] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [errorMessage, setErrorMessage] = useState<string>('');

  const [form] = Form.useForm();

  // 重置状态（不需要 form.resetFields()，destroyOnHidden 已自动清理表单内容）
  const resetState = useCallback(() => {
    setStep('email');
    setEmail('');
    setCode('');
    setCount(0);
    setLoading(false);
    setErrorMessage('');
  }, []);

  // 关闭时重置
  useEffect(() => {
    if (!open) {
      resetState();
    }
  }, [open, resetState]);

  // 倒计时
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (count > 0) {
      timer = setTimeout(() => setCount(count - 1), 1000);
    }
    return () => clearTimeout(timer);
  }, [count]);

  // 当前步骤索引
  const getCurrentStep = () => {
    switch (step) {
      case 'email': return 0;
      case 'verify': return 1;
      case 'reset': return 2;
      case 'success': return 3;
      default: return 0;
    }
  };

  // 第一步：发送验证码
  const handleSendCode = async (values: { email: string }) => {
    setErrorMessage('');
    setLoading(true);

    try {
      const response = await forgotPassword({
        email: values.email,
        language: getApiLanguage(intl.locale),
      });

      if (response.success) {
        setEmail(values.email);
        setStep('verify');
        setCount(59);
        message.success(response.message || intl.formatMessage({ id: 'pages.forgotPassword.codeSent', defaultMessage: '验证码已发送到您的邮箱' }));
      } else {
        const errorMsg = response.message || getErrorMessage(response.error?.code || '');
        setErrorMessage(errorMsg);
      }
    } catch (error: any) {
      setErrorMessage(extractErrorMessage(error, intl.formatMessage({ id: 'pages.forgotPassword.sendFailed', defaultMessage: '发送验证码失败，请重试' })));
    } finally {
      setLoading(false);
    }
  };

  // 第二步：验证验证码
  const handleVerifyCode = async (values: { code: string }) => {
    setCode(values.code);
    setStep('reset');
    setErrorMessage('');
  };

  // 第三步：重置密码
  const handleResetPassword = async (values: { newPassword: string }) => {
    setErrorMessage('');
    setLoading(true);

    try {
      const response = await resetPassword({
        email,
        code,
        newPassword: values.newPassword,
      });

      if (response.success) {
        setStep('success');
        message.success(intl.formatMessage({ id: 'pages.forgotPassword.resetSuccess', defaultMessage: '密码重置成功！' }));
      } else {
        const errorMsg = response.message || getErrorMessage(response.error?.code || '');
        setErrorMessage(errorMsg);
      }
    } catch (error: any) {
      setErrorMessage(extractErrorMessage(error, intl.formatMessage({ id: 'pages.forgotPassword.resetFailed', defaultMessage: '重置密码失败，请重试' })));
    } finally {
      setLoading(false);
    }
  };

  // 重发验证码
  const handleResendCode = async () => {
    try {
      const response = await resendForgotPasswordCode({
        email,
        language: getApiLanguage(intl.locale),
      });

      if (response.success) {
        setCount(59);
        message.success(intl.formatMessage({ id: 'pages.forgotPassword.codeResent', defaultMessage: '验证码已重新发送' }));
      } else {
        const errorMsg = response.message || getErrorMessage(response.error?.code || '');
        message.error(errorMsg);
      }
    } catch (error: any) {
      message.error(extractErrorMessage(error, intl.formatMessage({ id: 'pages.forgotPassword.sendCodeFailed', defaultMessage: '发送验证码失败' })));
    }
  };

  // 密码确认校验
  const checkConfirm = (_: any, value: string) => {
    if (value && value !== form.getFieldValue('newPassword')) {
      return Promise.reject(intl.formatMessage({ id: 'pages.forgotPassword.passwordMismatch', defaultMessage: '两次输入的密码不匹配!' }));
    }
    return Promise.resolve();
  };

  const handleClose = () => {
    onClose();
  };

  return (
    <Modal
      title={intl.formatMessage({ id: 'pages.forgotPassword.title', defaultMessage: '找回密码' })}
      open={open}
      onCancel={handleClose}
      footer={null}
      width={420}
      destroyOnHidden
    >
      {step !== 'success' && (
        <Steps
          className={styles.steps}
          current={getCurrentStep()}
          items={[
            { title: intl.formatMessage({ id: 'pages.forgotPassword.step1', defaultMessage: '验证邮箱' }) },
            { title: intl.formatMessage({ id: 'pages.forgotPassword.step2', defaultMessage: '验证码' }) },
            { title: intl.formatMessage({ id: 'pages.forgotPassword.step3', defaultMessage: '重置密码' }) },
          ]}
          size="small"
        />
      )}

      {errorMessage && (
        <Alert
          style={{ marginBottom: 16 }}
          message={errorMessage}
          type="error"
          showIcon
        />
      )}

      {step === 'email' && (
        <Form form={form} onFinish={handleSendCode} layout="vertical">
          <Form.Item
            name="email"
            label={intl.formatMessage({ id: 'pages.forgotPassword.email', defaultMessage: '注册邮箱' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'pages.forgotPassword.email.required', defaultMessage: '请输入邮箱地址' }) },
              { type: 'email', message: intl.formatMessage({ id: 'pages.forgotPassword.email.invalid', defaultMessage: '邮箱格式不正确' }) },
            ]}
          >
            <Input
              prefix={<MailOutlined />}
              placeholder={intl.formatMessage({ id: 'pages.forgotPassword.email.placeholder', defaultMessage: '请输入注册邮箱' })}
            />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0 }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
            >
              {intl.formatMessage({ id: 'pages.forgotPassword.sendCode', defaultMessage: '发送验证码' })}
            </Button>
          </Form.Item>
        </Form>
      )}

      {step === 'verify' && (
        <Form form={form} onFinish={handleVerifyCode} layout="vertical">
          <div style={{ marginBottom: 16 }}>
            {intl.formatMessage({ id: 'pages.forgotPassword.codeSentTo', defaultMessage: '验证码已发送到' })}{' '}
            <strong>{email}</strong>
          </div>

          <Row gutter={8}>
            <Col span={16}>
              <Form.Item
                name="code"
                rules={[
                  { required: true, message: intl.formatMessage({ id: 'pages.forgotPassword.code.required', defaultMessage: '请输入验证码' }) },
                  { len: 6, message: intl.formatMessage({ id: 'pages.forgotPassword.code.length', defaultMessage: '验证码为6位数字' }) },
                ]}
              >
                <Input
                  size="large"
                  prefix={<SafetyOutlined />}
                  placeholder={intl.formatMessage({ id: 'pages.forgotPassword.code.placeholder', defaultMessage: '6位验证码' })}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Button
                size="large"
                disabled={count > 0}
                className={styles.getCaptcha}
                onClick={handleResendCode}
              >
                {count > 0 ? `${count}s` : intl.formatMessage({ id: 'pages.forgotPassword.resend', defaultMessage: '重发' })}
              </Button>
            </Col>
          </Row>

          <Form.Item style={{ marginBottom: 0 }}>
            <Button
              type="primary"
              htmlType="submit"
              block
              size="large"
            >
              {intl.formatMessage({ id: 'pages.forgotPassword.next', defaultMessage: '下一步' })}
            </Button>
          </Form.Item>
        </Form>
      )}

      {step === 'reset' && (
        <Form form={form} onFinish={handleResetPassword} layout="vertical">
          <Form.Item
            name="newPassword"
            label={intl.formatMessage({ id: 'pages.forgotPassword.newPassword', defaultMessage: '新密码' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'pages.forgotPassword.newPassword.required', defaultMessage: '请输入新密码' }) },
              { min: 6, message: intl.formatMessage({ id: 'pages.forgotPassword.newPassword.minLength', defaultMessage: '密码至少6个字符' }) },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder={intl.formatMessage({ id: 'pages.forgotPassword.newPassword.placeholder', defaultMessage: '至少6位' })}
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            label={intl.formatMessage({ id: 'pages.forgotPassword.confirmPassword', defaultMessage: '确认新密码' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'pages.forgotPassword.confirmPassword.required', defaultMessage: '请确认新密码' }) },
              { validator: checkConfirm },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder={intl.formatMessage({ id: 'pages.forgotPassword.confirmPassword.placeholder', defaultMessage: '再次输入新密码' })}
            />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0 }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
            >
              {intl.formatMessage({ id: 'pages.forgotPassword.resetPassword', defaultMessage: '重置密码' })}
            </Button>
          </Form.Item>
        </Form>
      )}

      {step === 'success' && (
        <Result
          status="success"
          title={intl.formatMessage({ id: 'pages.forgotPassword.successTitle', defaultMessage: '密码重置成功' })}
          subTitle={intl.formatMessage({ id: 'pages.forgotPassword.successSubtitle', defaultMessage: '请使用新密码登录' })}
          extra={
            <Button type="primary" onClick={handleClose}>
              {intl.formatMessage({ id: 'pages.forgotPassword.backToLogin', defaultMessage: '返回登录' })}
            </Button>
          }
        />
      )}
    </Modal>
  );
};

export default ForgotPasswordModal;
