import { history, Link, useIntl } from '@umijs/max';
import {
  Alert,
  App,
  Button,
  Col,
  Form,
  Input,
  Popover,
  Progress,
  Row,
} from 'antd';
import type { FC } from 'react';
import { useEffect, useState } from 'react';
import {
  preRegister,
  verifyRegister,
  resendRegisterCode,
} from '@/services/auth/api';
import { getErrorMessage } from '@/services/auth/errorCodes';
import useStyles from './styles';

const FormItem = Form.Item;

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

// 注册步骤
type RegisterStep = 'form' | 'verify';

const Register: FC = () => {
  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 [open, setVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [errorMessage, setErrorMessage] = useState<string>('');

  let interval: number | undefined;

  const passwordStatusMap = {
    ok: (
      <div className={styles.success}>
        <span>强度：强</span>
      </div>
    ),
    pass: (
      <div className={styles.warning}>
        <span>强度：中</span>
      </div>
    ),
    poor: (
      <div className={styles.error}>
        <span>强度：太短</span>
      </div>
    ),
  };

  const [form] = Form.useForm();
  const [verifyForm] = Form.useForm();

  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 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) => {
    const promise = Promise;
    if (value && value !== form.getFieldValue('password')) {
      return promise.reject('两次输入的密码不匹配!');
    }
    return promise.resolve();
  };

  const checkPassword = (_: any, value: string) => {
    const promise = Promise;
    if (!value) {
      setVisible(!!value);
      return promise.reject('请输入密码!');
    }
    if (!open) {
      setVisible(!!value);
    }
    if (value.length < 6) {
      return promise.reject('密码至少6个字符');
    }
    return promise.resolve();
  };

  const renderPasswordProgress = () => {
    const value = form.getFieldValue('password');
    const passwordStatus = getPasswordStatus();
    return value?.length ? (
      <div
        className={styles[`progress-${passwordStatus}` 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: 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 handleVerifyRegister = async (values: { code: string }) => {
    setErrorMessage('');
    setLoading(true);

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

      if (response.success) {
        message.success('注册成功！');
        history.push(`/user/register-result?account=${email}`);
      } 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 resendRegisterCode({
        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 handleBack = () => {
    setStep('form');
    setErrorMessage('');
  };

  return (
    <div className={styles.main}>
      <h3>注册</h3>

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

      {step === 'form' ? (
        <Form form={form} name="UserRegister" onFinish={handlePreRegister}>
          <FormItem
            name="username"
            rules={[
              {
                required: true,
                message: '请输入用户名!',
              },
              {
                min: 3,
                max: 30,
                message: '用户名长度为3-30个字符',
              },
            ]}
          >
            <Input size="large" placeholder="用户名（3-30个字符）" />
          </FormItem>

          <FormItem
            name="email"
            rules={[
              {
                required: true,
                message: '请输入邮箱地址!',
              },
              {
                type: 'email',
                message: '邮箱地址格式错误!',
              },
            ]}
          >
            <Input size="large" placeholder="邮箱" />
          </FormItem>

          <FormItem
            name="nickname"
          >
            <Input size="large" placeholder="昵称（可选）" />
          </FormItem>

          <Popover
            getPopupContainer={(node) => {
              if (node?.parentNode) {
                return node.parentNode as HTMLElement;
              }
              return node;
            }}
            content={
              open && (
                <div
                  style={{
                    padding: '4px 0',
                  }}
                >
                  {passwordStatusMap[getPasswordStatus()]}
                  {renderPasswordProgress()}
                  <div
                    style={{
                      marginTop: 10,
                    }}
                  >
                    <span>请至少输入 6 个字符。请不要使用容易被猜到的密码。</span>
                  </div>
                </div>
              )
            }
            styles={{ root: { width: 240 } }}
            placement="right"
            open={open}
          >
            <FormItem
              name="password"
              className={
                form.getFieldValue('password') &&
                form.getFieldValue('password').length > 0
                  ? styles.password
                  : ''
              }
              rules={[
                {
                  validator: checkPassword,
                },
              ]}
            >
              <Input.Password
                size="large"
                placeholder="至少6位密码，区分大小写"
              />
            </FormItem>
          </Popover>

          <FormItem
            name="confirm"
            rules={[
              {
                required: true,
                message: '请确认密码',
              },
              {
                validator: checkConfirm,
              },
            ]}
          >
            <Input.Password size="large" placeholder="确认密码" />
          </FormItem>

          <FormItem
            name="referralCode"
          >
            <Input size="large" placeholder="推荐码（可选）" />
          </FormItem>

          <FormItem>
            <div className={styles.footer}>
              <Button
                size="large"
                loading={loading}
                className={styles.submit}
                type="primary"
                htmlType="submit"
              >
                <span>注册</span>
              </Button>
              <Link to="/user/login">
                <span>使用已有账户登录</span>
              </Link>
            </div>
          </FormItem>
        </Form>
      ) : (
        <Form form={verifyForm} name="VerifyRegister" onFinish={handleVerifyRegister}>
          <div style={{ marginBottom: 24 }}>
            <span>验证码已发送到 </span>
            <strong>{email}</strong>
            <Button type="link" onClick={handleBack} style={{ padding: 0, marginLeft: 8 }}>
              修改信息
            </Button>
          </div>

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

          <FormItem>
            <div className={styles.footer}>
              <Button
                size="large"
                loading={loading}
                className={styles.submit}
                type="primary"
                htmlType="submit"
              >
                <span>验证并注册</span>
              </Button>
            </div>
          </FormItem>
        </Form>
      )}
    </div>
  );
};

export default Register;
