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

const useStyles = createStyles(({ token }) => ({
  main: {
    width: 368,
    margin: '0 auto',
    padding: '36px 0',
  },
  header: {
    textAlign: 'center',
    marginBottom: 40,
  },
  title: {
    fontSize: 24,
    fontWeight: 600,
    marginBottom: 8,
  },
  subtitle: {
    color: token.colorTextSecondary,
  },
  steps: {
    marginBottom: 32,
  },
  footer: {
    marginTop: 24,
    textAlign: 'center',
  },
  getCaptcha: {
    width: '100%',
  },
}));

// 重置密码步骤
type ResetStep = 'email' | 'verify' | 'reset' | 'success';

const ForgotPassword: FC = () => {
  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 [emailForm] = Form.useForm();
  const [verifyForm] = Form.useForm();
  const [resetForm] = Form.useForm();

  let interval: number | undefined;

  useEffect(
    () => () => {
      clearInterval(interval);
    },
    [interval],
  );

  // 开始倒计时
  const startCountdown = () => {
    let counts = 59;
    setCount(counts);
    interval = window.setInterval(() => {
      counts -= 1;
      setCount(counts);
      if (counts === 0) {
        clearInterval(interval);
      }
    }, 1000);
  };

  // 当前步骤索引
  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: intl.locale === 'zh-CN' ? 'zh' : 'en',
      });

      if (response.success) {
        setEmail(values.email);
        setStep('verify');
        startCountdown();
        message.success(response.message || '验证码已发送到您的邮箱');
      } else {
        const errorMsg = response.message || getErrorMessage(response.error?.code || '');
        setErrorMessage(errorMsg);
      }
    } catch (error: any) {
      const errorMsg = error?.message || '发送验证码失败，请重试';
      setErrorMessage(errorMsg);
    } 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('密码重置成功！');
      } else {
        const errorMsg = response.message || getErrorMessage(response.error?.code || '');
        setErrorMessage(errorMsg);
      }
    } catch (error: any) {
      const errorMsg = error?.message || '重置密码失败，请重试';
      setErrorMessage(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  // 重发验证码
  const handleResendCode = async () => {
    try {
      const response = await resendForgotPasswordCode({
        email,
        language: intl.locale === 'zh-CN' ? 'zh' : 'en',
      });

      if (response.success) {
        startCountdown();
        message.success('验证码已重新发送');
      } else {
        const errorMsg = response.message || getErrorMessage(response.error?.code || '');
        message.error(errorMsg);
      }
    } catch (error: any) {
      message.error(error?.message || '发送验证码失败');
    }
  };

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

  return (
    <div className={styles.main}>
      <div className={styles.header}>
        <h2 className={styles.title}>找回密码</h2>
        <p className={styles.subtitle}>通过邮箱验证重置您的密码</p>
      </div>

      <Steps
        className={styles.steps}
        current={getCurrentStep()}
        items={[
          { title: '验证邮箱' },
          { title: '输入验证码' },
          { title: '重置密码' },
          { title: '完成' },
        ]}
        size="small"
      />

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

      {step === 'email' && (
        <Form form={emailForm} onFinish={handleSendCode}>
          <Form.Item
            name="email"
            rules={[
              { required: true, message: '请输入邮箱地址' },
              { type: 'email', message: '邮箱格式不正确' },
            ]}
          >
            <Input
              size="large"
              prefix={<MailOutlined />}
              placeholder="请输入注册邮箱"
            />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              loading={loading}
              block
            >
              发送验证码
            </Button>
          </Form.Item>
        </Form>
      )}

      {step === 'verify' && (
        <Form form={verifyForm} onFinish={handleVerifyCode}>
          <div style={{ marginBottom: 16 }}>
            <span>验证码已发送到 </span>
            <strong>{email}</strong>
          </div>

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

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              block
            >
              下一步
            </Button>
          </Form.Item>
        </Form>
      )}

      {step === 'reset' && (
        <Form form={resetForm} onFinish={handleResetPassword}>
          <Form.Item
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码至少6个字符' },
            ]}
          >
            <Input.Password
              size="large"
              prefix={<LockOutlined />}
              placeholder="新密码（至少6位）"
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            rules={[
              { required: true, message: '请确认新密码' },
              { validator: checkConfirm },
            ]}
          >
            <Input.Password
              size="large"
              prefix={<LockOutlined />}
              placeholder="确认新密码"
            />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              loading={loading}
              block
            >
              重置密码
            </Button>
          </Form.Item>
        </Form>
      )}

      {step === 'success' && (
        <div style={{ textAlign: 'center' }}>
          <Alert
            type="success"
            message="密码重置成功"
            description="您的密码已成功重置，请使用新密码登录。"
            showIcon
            style={{ marginBottom: 24 }}
          />
          <Button
            type="primary"
            size="large"
            onClick={() => history.push('/user/login')}
          >
            返回登录
          </Button>
        </div>
      )}

      <div className={styles.footer}>
        <Link to="/user/login">返回登录</Link>
      </div>
    </div>
  );
};

export default ForgotPassword;
