import { GoogleOutlined, LockOutlined, MailOutlined } from '@ant-design/icons';
import type { ProFormCaptchaProps } from '@ant-design/pro-components';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormText,
} from '@ant-design/pro-components';
import {
  FormattedMessage,
  Helmet,
  SelectLang,
  useIntl,
  useModel,
} from '@umijs/max';
import { Alert, App, Button, Divider } from 'antd';
import { createStyles } from 'antd-style';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import { Footer } from '@/components';
import {
  googleLogin,
  preLogin,
  resendLoginCode,
  verifyLogin,
} from '@/services/auth/api';
import {
  extractErrorMessage,
  getApiLanguage,
  getErrorMessage,
} from '@/services/auth/errorCodes';
import { captureReferralCodeFromUrl, getCachedReferralCode } from '@/utils/referralCode';
import Settings from '../../../../config/defaultSettings';
import ForgotPasswordModal from './components/ForgotPasswordModal';
import RegisterModal from './components/RegisterModal';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});

// 登录步骤
type LoginStep = 'credentials' | 'verify';

const Lang = () => {
  const { styles } = useStyles();

  return (
    <div className={styles.lang} data-lang>
      {SelectLang && <SelectLang />}
    </div>
  );
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [loginStep, setLoginStep] = useState<LoginStep>('credentials');
  const [email, setEmail] = useState<string>('');
  const [errorMessage, setErrorMessage] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const [registerModalOpen, setRegisterModalOpen] = useState<boolean>(false);
  const [forgotPasswordModalOpen, setForgotPasswordModalOpen] =
    useState<boolean>(false);
  const [countdown, setCountdown] = useState<number>(0);
  const countdownTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const { message } = App.useApp();
  const intl = useIntl();

  // 开始倒计时
  const startCountdown = useCallback((seconds: number = 60) => {
    // 清除之前的定时器
    if (countdownTimerRef.current) {
      clearInterval(countdownTimerRef.current);
    }
    setCountdown(seconds);
    countdownTimerRef.current = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          if (countdownTimerRef.current) {
            clearInterval(countdownTimerRef.current);
            countdownTimerRef.current = null;
          }
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  }, []);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (countdownTimerRef.current) {
        clearInterval(countdownTimerRef.current);
      }
    };
  }, []);

  const fetchUserInfo = useCallback(async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  }, [initialState, setInitialState]);

  // 存储 Google OAuth 的 idToken（用于处理弹窗回调）
  const [googleIdToken, setGoogleIdToken] = useState<string | null>(null);

  // 捕获 URL 中的邀请码并存入缓存
  useEffect(() => {
    captureReferralCodeFromUrl();
  }, []);

  // 第一步：检测 URL hash 中的 id_token
  useEffect(() => {
    const hash = window.location.hash;
    if (!hash || !hash.includes('id_token=')) {
      return;
    }

    // 从 URL fragment 中提取 id_token
    const params = new URLSearchParams(hash.substring(1));
    const idToken = params.get('id_token');

    if (idToken) {
      // 清除 URL 中的 hash，防止刷新时重复处理
      window.history.replaceState(
        null,
        '',
        window.location.pathname + window.location.search,
      );
      // 设置 token，触发登录
      setGoogleIdToken(idToken);
    }
  }, []);

  // 第二步：当 googleIdToken 变化时，执行登录
  useEffect(() => {
    if (!googleIdToken) {
      return;
    }

    const doGoogleLogin = async () => {
      setLoading(true);
      try {
        // 获取缓存的邀请码
        const referralCode = getCachedReferralCode();
        const result = await googleLogin({
          idToken: googleIdToken,
          referralCode: referralCode || undefined,
        });

        if (result.success) {
          message.success(
            intl.formatMessage({
              id: 'pages.login.googleSuccess',
              defaultMessage: 'Google 登录成功',
            }),
          );
          await fetchUserInfo();

          // 获取跳转地址
          const urlParams = new URL(window.location.href).searchParams;
          const redirect = urlParams.get('redirect') || '/';

          // 如果是弹窗，关闭弹窗并刷新父窗口
          if (window.opener && window.opener !== window) {
            try {
              window.opener.location.href = redirect;
            } catch (e) {
              // 跨域时无法操作父窗口，父窗口需要自己刷新
            }
            window.close();
            return;
          }

          // 非弹窗模式，直接跳转
          window.location.href = redirect;
        } else {
          const errorMsg =
            result.message || getErrorMessage(result.error?.code || '');
          message.error(errorMsg);
        }
      } catch (error: any) {
        message.error(
          extractErrorMessage(
            error,
            intl.formatMessage({
              id: 'pages.login.googleFailed',
              defaultMessage: 'Google 登录失败',
            }),
          ),
        );
      } finally {
        setLoading(false);
        setGoogleIdToken(null);
      }
    };

    doGoogleLogin();
  }, [googleIdToken, message, intl, fetchUserInfo]);

  // 第一步：提交邮箱和密码
  const handlePreLogin = async (values: {
    email: string;
    password: string;
  }) => {
    setErrorMessage('');
    setLoading(true);

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

      if (response.success) {
        setEmail(values.email);
        setLoginStep('verify');
        startCountdown(60); // 开始60秒倒计时
        message.success(
          response.message ||
            intl.formatMessage({
              id: 'pages.login.codeSent',
              defaultMessage: '验证码已发送到您的邮箱',
            }),
        );
      } else {
        const errorMsg =
          response.message || getErrorMessage(response.error?.code || '');
        setErrorMessage(errorMsg);
      }
    } catch (error: any) {
      setErrorMessage(
        extractErrorMessage(
          error,
          intl.formatMessage({
            id: 'pages.login.requestFailed',
            defaultMessage: '登录请求失败，请重试',
          }),
        ),
      );
    } finally {
      setLoading(false);
    }
  };

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

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

      if (response.success) {
        message.success(
          intl.formatMessage({
            id: 'pages.login.success',
            defaultMessage: '登录成功！',
          }),
        );

        // 刷新用户信息并跳转
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        const redirect = urlParams.get('redirect') || '/';
        window.location.href = redirect;
      } else {
        const errorMsg =
          response.message || getErrorMessage(response.error?.code || '');
        setErrorMessage(errorMsg);
      }
    } catch (error: any) {
      setErrorMessage(
        extractErrorMessage(
          error,
          intl.formatMessage({
            id: 'pages.login.verifyFailed',
            defaultMessage: '验证失败，请重试',
          }),
        ),
      );
    } finally {
      setLoading(false);
    }
  };

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

      if (response.success) {
        startCountdown(60); // 重发后开始60秒倒计时
        message.success(
          intl.formatMessage({
            id: 'pages.login.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.login.sendCodeFailed',
            defaultMessage: '发送验证码失败',
          }),
        ),
      );
    }
  };

  // Google 登录 - 弹窗模式
  const handleGoogleLogin = () => {
    const redirectUri = window.location.origin + '/user/login';
    const oauth2Url =
      `https://accounts.google.com/o/oauth2/v2/auth?` +
      `client_id=${process.env.GOOGLE_CLIENT_ID}` +
      `&redirect_uri=${encodeURIComponent(redirectUri)}` +
      `&response_type=id_token` +
      `&scope=openid email profile` +
      `&nonce=${Math.random().toString(36).substring(2)}` +
      `&prompt=select_account`;

    // 弹窗打开 Google 登录
    window.open(
      oauth2Url,
      'googleLogin',
      'width=500,height=600,left=200,top=100',
    );
  };

  // 返回上一步（重新登录）
  const handleBack = () => {
    setLoginStep('credentials');
    setErrorMessage('');
    setCountdown(0);
    if (countdownTimerRef.current) {
      clearInterval(countdownTimerRef.current);
      countdownTimerRef.current = null;
    }
  };

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录',
          })}
          {Settings.title && ` - ${Settings.title}`}
        </title>
      </Helmet>
      <Lang />
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={null}
          title="Sofio Admin"
          subTitle=" "
          submitter={{
            searchConfig: {
              submitText:
                loginStep === 'credentials'
                  ? intl.formatMessage({
                      id: 'pages.login.submit',
                      defaultMessage: '登录',
                    })
                  : intl.formatMessage({
                      id: 'pages.login.verify',
                      defaultMessage: '验证',
                    }),
            },
            submitButtonProps: {
              loading,
              size: 'large',
              style: { width: '100%' },
            },
          }}
          actions={
            loginStep === 'credentials' && (
              <div style={{ width: '100%' }}>
                <div
                  style={{
                    marginTop: 16,
                    marginBottom: 16,
                    textAlign: 'center',
                  }}
                >
                  <FormattedMessage
                    id="pages.login.noAccount"
                    defaultMessage="还没有账号？"
                  />
                  <Button
                    type="link"
                    style={{ padding: 0 }}
                    onClick={() => setRegisterModalOpen(true)}
                  >
                    <FormattedMessage
                      id="pages.login.register"
                      defaultMessage="立即注册"
                    />
                  </Button>
                </div>
                <Divider plain style={{ marginTop: 0, marginBottom: 16 }}>
                  <FormattedMessage
                    id="pages.login.loginWith"
                    defaultMessage="其他登录方式"
                  />
                </Divider>
                <Button
                  icon={<GoogleOutlined />}
                  onClick={handleGoogleLogin}
                  size="large"
                  block
                >
                  <FormattedMessage
                    id="pages.login.googleLogin"
                    defaultMessage="使用 Google 账号登录"
                  />
                </Button>
              </div>
            )
          }
          onFinish={async (values) => {
            if (loginStep === 'credentials') {
              await handlePreLogin(
                values as { email: string; password: string },
              );
            } else {
              await handleVerifyLogin(values as { code: string });
            }
          }}
        >
          {errorMessage && <LoginMessage content={errorMessage} />}

          {loginStep === 'credentials' ? (
            <>
              <ProFormText
                name="email"
                fieldProps={{
                  size: 'large',
                  prefix: <MailOutlined />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.email.placeholder',
                  defaultMessage: '请输入邮箱',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.email.required"
                        defaultMessage="请输入邮箱！"
                      />
                    ),
                  },
                  {
                    type: 'email',
                    message: (
                      <FormattedMessage
                        id="pages.login.email.invalid"
                        defaultMessage="邮箱格式不正确！"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.password.placeholder',
                  defaultMessage: '请输入密码',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                ]}
              />

              <div
                style={{
                  marginBottom: 24,
                  textAlign: 'right',
                }}
              >
                <Button
                  type="link"
                  style={{ padding: 0 }}
                  onClick={() => setForgotPasswordModalOpen(true)}
                >
                  <FormattedMessage
                    id="pages.login.forgotPassword"
                    defaultMessage="忘记密码"
                  />
                </Button>
              </div>
            </>
          ) : (
            <>
              <div style={{ marginBottom: 24 }}>
                <FormattedMessage
                  id="pages.login.codeSentTo"
                  defaultMessage="验证码已发送到"
                />{' '}
                <strong>{email}</strong>
                <Button
                  type="link"
                  onClick={handleBack}
                  style={{ padding: 0, marginLeft: 8 }}
                >
                  <FormattedMessage
                    id="pages.login.reLogin"
                    defaultMessage="重新登录"
                  />
                </Button>
              </div>

              <ProFormCaptcha
                name="code"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                captchaProps={{
                  size: 'large',
                  disabled: countdown > 0,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.captcha.placeholder',
                  defaultMessage: '请输入验证码',
                })}
                captchaTextRender={() => {
                  if (countdown > 0) {
                    return intl.formatMessage(
                      {
                        id: 'pages.login.resendAfter',
                        defaultMessage: '{count} 秒后重发',
                      },
                      { count: countdown },
                    );
                  }
                  return intl.formatMessage({
                    id: 'pages.login.resend',
                    defaultMessage: '重新发送',
                  });
                }}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.captcha.required"
                        defaultMessage="请输入验证码！"
                      />
                    ),
                  },
                  {
                    len: 6,
                    message: intl.formatMessage({
                      id: 'pages.login.captcha.length',
                      defaultMessage: '验证码为6位数字',
                    }),
                  },
                ]}
                onGetCaptcha={async () => {
                  if (countdown > 0) return;
                  await handleResendCode();
                }}
              />
            </>
          )}
        </LoginForm>
      </div>
      <Footer />

      {/* 注册弹窗 */}
      <RegisterModal
        open={registerModalOpen}
        onClose={() => setRegisterModalOpen(false)}
        onSuccess={async () => {
          // 注册成功后直接登录（API 已返回 tokens 并保存）
          await fetchUserInfo();
          const urlParams = new URL(window.location.href).searchParams;
          const redirect = urlParams.get('redirect') || '/';
          window.location.href = redirect;
        }}
      />

      {/* 忘记密码弹窗 */}
      <ForgotPasswordModal
        open={forgotPasswordModalOpen}
        onClose={() => setForgotPasswordModalOpen(false)}
      />
    </div>
  );
};

export default Login;
