import { useIntl } from '@umijs/max';
import {
  Alert,
  App,
  Button,
  Col,
  Form,
  Input,
  Modal,
  Popover,
  Progress,
  Row,
} from 'antd';
import React, { useEffect, useState, useCallback } from 'react';
import { createStyles } from 'antd-style';
import {
  preRegister,
  verifyRegister,
  resendRegisterCode,
} from '@/services/auth/api';
import { getErrorMessage, extractErrorMessage, getApiLanguage } from '@/services/auth/errorCodes';
import { getCachedReferralCode } from '@/utils/referralCode';

const useStyles = createStyles(({ token }) => ({
  success: {
    color: token.colorSuccess,
  },
  warning: {
    color: token.colorWarning,
  },
  error: {
    color: token.colorError,
  },
  progressPass: {
    '.ant-progress-bg': { backgroundColor: token.colorWarning },
  },
  progressOk: {
    '.ant-progress-bg': { backgroundColor: token.colorSuccess },
  },
  progressPoor: {
    '.ant-progress-bg': { backgroundColor: token.colorError },
  },
  getCaptcha: {
    width: '100%',
  },
}));

const passwordProgressMap: {
  ok: 'success';
  pass: 'normal';
  poor: 'exception';
} = {
  ok: 'success',
  pass: 'normal',
  poor: 'exception',
};

interface RegisterModalProps {
  open: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

type RegisterStep = 'form' | 'verify';

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

  const [step, setStep] = useState<RegisterStep>('form');
  const [email, setEmail] = useState<string>('');
  const [count, setCount] = useState<number>(0);
  const [popoverOpen, setPopoverOpen] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [errorMessage, setErrorMessage] = useState<string>('');
  const [cachedReferralCode, setCachedReferralCode] = useState<string | null>(null);

  const [form] = Form.useForm();

  // 加载缓存的邀请码
  useEffect(() => {
    if (open) {
      const code = getCachedReferralCode();
      setCachedReferralCode(code);
      if (code) {
        form.setFieldValue('referralCode', code);
      }
    }
  }, [open, form]);

  // 重置状态（不需要 form.resetFields()，destroyOnHidden 已自动清理表单内容）
  const resetState = useCallback(() => {
    setStep('form');
    setEmail('');
    setCount(0);
    setPopoverOpen(false);
    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 passwordStatusMap = {
    ok: <div className={styles.success}>{intl.formatMessage({ id: 'pages.register.password.strong', defaultMessage: '强度：强' })}</div>,
    pass: <div className={styles.warning}>{intl.formatMessage({ id: 'pages.register.password.medium', defaultMessage: '强度：中' })}</div>,
    poor: <div className={styles.error}>{intl.formatMessage({ id: 'pages.register.password.weak', defaultMessage: '强度：太短' })}</div>,
  };

  const getPasswordStatus = () => {
    const value = form.getFieldValue('password');
    if (value && value.length > 9) return 'ok';
    if (value && value.length > 5) return 'pass';
    return 'poor';
  };

  const checkConfirm = (_: any, value: string) => {
    if (value && value !== form.getFieldValue('password')) {
      return Promise.reject(intl.formatMessage({ id: 'pages.register.password.mismatch', defaultMessage: '两次输入的密码不匹配!' }));
    }
    return Promise.resolve();
  };

  const checkPassword = (_: any, value: string) => {
    if (!value) {
      setPopoverOpen(!!value);
      return Promise.reject(intl.formatMessage({ id: 'pages.register.password.required', defaultMessage: '请输入密码!' }));
    }
    if (!popoverOpen) {
      setPopoverOpen(!!value);
    }
    if (value.length < 6) {
      return Promise.reject(intl.formatMessage({ id: 'pages.register.password.minLength', defaultMessage: '密码至少6个字符' }));
    }
    return Promise.resolve();
  };

  const renderPasswordProgress = () => {
    const value = form.getFieldValue('password');
    const passwordStatus = getPasswordStatus();
    return value?.length ? (
      <div className={styles[`progress${passwordStatus.charAt(0).toUpperCase() + passwordStatus.slice(1)}` as keyof typeof styles]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          strokeWidth={6}
          percent={value.length * 10 > 100 ? 100 : value.length * 10}
          showInfo={false}
        />
      </div>
    ) : null;
  };

  // 第一步：提交注册表单
  const handlePreRegister = async (values: {
    username: string;
    email: string;
    password: string;
    nickname?: string;
    referralCode?: string;
  }) => {
    setErrorMessage('');
    setLoading(true);

    try {
      const response = await preRegister({
        username: values.username,
        email: values.email,
        password: values.password,
        nickname: values.nickname,
        referralCode: values.referralCode,
        language: getApiLanguage(intl.locale),
      });

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

  // 第二步：验证验证码
  const handleVerifyRegister = async (values: { code: string }) => {
    setErrorMessage('');
    setLoading(true);

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

      if (response.success) {
        message.success(intl.formatMessage({ id: 'pages.register.success', defaultMessage: '注册成功！' }));
        onClose();
        onSuccess?.();
      } else {
        const errorMsg = response.message || getErrorMessage(response.error?.code || '');
        setErrorMessage(errorMsg);
      }
    } catch (error: any) {
      setErrorMessage(extractErrorMessage(error, intl.formatMessage({ id: 'pages.register.verifyFailed', defaultMessage: '验证失败，请重试' })));
    } finally {
      setLoading(false);
    }
  };

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

      if (response.success) {
        setCount(59);
        message.success(intl.formatMessage({ id: 'pages.register.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.register.sendCodeFailed', defaultMessage: '发送验证码失败' })));
    }
  };

  // 返回上一步
  const handleBack = () => {
    setStep('form');
    setErrorMessage('');
  };

  return (
    <Modal
      title={intl.formatMessage({ id: 'pages.register.title', defaultMessage: '注册账号' })}
      open={open}
      onCancel={onClose}
      footer={null}
      width={420}
      destroyOnHidden
    >
      {errorMessage && (
        <Alert
          style={{ marginBottom: 16 }}
          message={errorMessage}
          type="error"
          showIcon
        />
      )}

      {step === 'form' ? (
        <Form form={form} onFinish={handlePreRegister} layout="vertical">
          <Form.Item
            name="username"
            label={intl.formatMessage({ id: 'pages.register.username', defaultMessage: '用户名' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'pages.register.username.required', defaultMessage: '请输入用户名!' }) },
              { min: 3, max: 30, message: intl.formatMessage({ id: 'pages.register.username.length', defaultMessage: '用户名长度为3-30个字符' }) },
            ]}
          >
            <Input placeholder={intl.formatMessage({ id: 'pages.register.username.placeholder', defaultMessage: '3-30个字符' })} />
          </Form.Item>

          <Form.Item
            name="email"
            label={intl.formatMessage({ id: 'pages.register.email', defaultMessage: '邮箱' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'pages.register.email.required', defaultMessage: '请输入邮箱地址!' }) },
              { type: 'email', message: intl.formatMessage({ id: 'pages.register.email.invalid', defaultMessage: '邮箱地址格式错误!' }) },
            ]}
          >
            <Input placeholder={intl.formatMessage({ id: 'pages.register.email.placeholder', defaultMessage: '请输入邮箱' })} />
          </Form.Item>

          <Form.Item name="nickname" label={intl.formatMessage({ id: 'pages.register.nickname', defaultMessage: '昵称' })}>
            <Input placeholder={intl.formatMessage({ id: 'pages.register.optional', defaultMessage: '可选' })} />
          </Form.Item>

          <Popover
            content={
              popoverOpen && (
                <div style={{ padding: '4px 0' }}>
                  {passwordStatusMap[getPasswordStatus()]}
                  {renderPasswordProgress()}
                  <div style={{ marginTop: 10, fontSize: 12, color: '#999' }}>
                    {intl.formatMessage({ id: 'pages.register.password.hint', defaultMessage: '请至少输入 6 个字符' })}
                  </div>
                </div>
              )
            }
            styles={{ root: { width: 200 } }}
            placement="right"
            open={popoverOpen}
          >
            <Form.Item
              name="password"
              label={intl.formatMessage({ id: 'pages.register.password', defaultMessage: '密码' })}
              rules={[{ validator: checkPassword }]}
            >
              <Input.Password placeholder={intl.formatMessage({ id: 'pages.register.password.placeholder', defaultMessage: '至少6位' })} />
            </Form.Item>
          </Popover>

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

          <Form.Item name="referralCode" label={intl.formatMessage({ id: 'pages.register.referralCode', defaultMessage: '推荐码' })}>
            <Input
              placeholder={intl.formatMessage({ id: 'pages.register.optional', defaultMessage: '可选' })}
              readOnly={!!cachedReferralCode}
              style={cachedReferralCode ? { backgroundColor: '#f5f5f5', cursor: 'not-allowed' } : undefined}
            />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0 }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
            >
              {intl.formatMessage({ id: 'pages.register.submit', defaultMessage: '注册' })}
            </Button>
          </Form.Item>
        </Form>
      ) : (
        <Form form={form} onFinish={handleVerifyRegister} layout="vertical">
          <div style={{ marginBottom: 16 }}>
            {intl.formatMessage({ id: 'pages.register.codeSentTo', defaultMessage: '验证码已发送到' })}{' '}
            <strong>{email}</strong>
            <Button type="link" onClick={handleBack} style={{ padding: 0, marginLeft: 8 }}>
              {intl.formatMessage({ id: 'pages.register.modifyInfo', defaultMessage: '修改信息' })}
            </Button>
          </div>

          <Row gutter={8}>
            <Col span={16}>
              <Form.Item
                name="code"
                rules={[
                  { required: true, message: intl.formatMessage({ id: 'pages.register.code.required', defaultMessage: '请输入验证码!' }) },
                  { len: 6, message: intl.formatMessage({ id: 'pages.register.code.length', defaultMessage: '验证码为6位数字' }) },
                ]}
              >
                <Input size="large" placeholder={intl.formatMessage({ id: 'pages.register.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.register.resend', defaultMessage: '重发' })}
              </Button>
            </Col>
          </Row>

          <Form.Item style={{ marginBottom: 0 }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
            >
              {intl.formatMessage({ id: 'pages.register.verifyAndRegister', defaultMessage: '验证并注册' })}
            </Button>
          </Form.Item>
        </Form>
      )}
    </Modal>
  );
};

export default RegisterModal;
