import { useState, type JSX } from 'react';
import { LoginRegisterForm } from './LoginRegiserForm';
import type { AuthMode, AuthStep, AuthType } from '../../types/authTypes';
import { OtpVerifyForm } from './OtpVerifyForm';
import { isNumeric } from '@/utils/regexes/isNumeric';
import { CompleteSignUp } from './CompleteSignUp';
import { EnterPasswordForm } from './EnterPasswordForm';
import { UserStatus } from '../../types/userTypes';
import type { CountryCode } from '@/types/commonTypes';
import { VerifyPhoneNumber } from './VerifyPhoneNumber';
import { useNavigate, useSearchParams } from 'react-router-dom';

export const AuthenticationSteps = (): JSX.Element => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const authReturnUrl: string | null = searchParams.get('returnUrl');
  const authReturnUrlOrDefault: string =
    authReturnUrl ?? import.meta.env.VITE_DEFUALT_AUTH_RETURN_URL;
  const [authMode, setAuthMode] = useState<AuthMode>('register');
  const [authType, setAuthType] = useState<AuthType>('phone');
  const [currentStep, setCurrentStep] = useState<AuthStep>('emailOrPhone');
  const [loginRegisterValue, setLoginRegisterValue] = useState<string>('');
  const [countryCode, setCountryCode] = useState<CountryCode>('+98');
  const [addPhoneCountryCode, setAddPhoneCountryCode] =
    useState<CountryCode>('+98');
  const [addedPhoneNumberValue, setAddedPhoneNumberValue] =
    useState<string>('');

  const handleLoginRegister = (value: string, userStatus: UserStatus) => {
    setAuthType(isNumeric(value) ? 'phone' : 'email');

    switch (userStatus) {
      case UserStatus.NotRegistered:
        setAuthMode('register');
        setCurrentStep('verify');
        break;

      case UserStatus.RegisteredWithoutPassword:
        setAuthMode('login');
        setCurrentStep('verify');

        break;

      case UserStatus.RegisteredWithPassword:
        setAuthMode('login');
        setCurrentStep('enterPassword');

        break;
    }
  };

  const handleUserLoggedIn = () => {
    redirectToReturnUrl();
  };

  const handleConfrimPhoneNumber = () => {
    setCurrentStep('addPhoneNumber');
  };

  const handlePhoneNumberVerified = () => {
    if (authReturnUrl) {
      navigate(`/signup?returnUrl=${authReturnUrl}`);
    } else {
      navigate(`/signup`);
    }
  };

  const redirectToReturnUrl = () => {
    if (!authReturnUrl) {
      navigate(import.meta.env.VITE_DEFUALT_AUTH_RETURN_URL);
    } else {
      if (authMode === 'register') {
        navigate(`/account-created?returnUrl=${authReturnUrl}`);
      } else {
        location.href = authReturnUrl;
      }
    }
  };

  return (
    <>
      {currentStep === 'emailOrPhone' && (
        <LoginRegisterForm
          authReturnUrl={authReturnUrlOrDefault}
          onGoogleAuthenticated={handleUserLoggedIn}
          countryCode={countryCode}
          setCountryCode={setCountryCode}
          loginRegisterValue={loginRegisterValue}
          setLoginRegisterValue={setLoginRegisterValue}
          authType={authType}
          setAuthType={setAuthType}
          onLoginRegisterSubmit={handleLoginRegister}
        />
      )}

      {currentStep === 'verify' && (
        <OtpVerifyForm
          onVerifyPhoneNumber={handleConfrimPhoneNumber}
          authReturnUrl={authReturnUrlOrDefault}
          countryCode={countryCode}
          onOTPVerified={handleUserLoggedIn}
          onEditValue={() => setCurrentStep('emailOrPhone')}
          authMode={authMode}
          authType={authType}
          value={loginRegisterValue}
        />
      )}

      {currentStep === 'enterPassword' && (
        <EnterPasswordForm
          authReturnUrl={authReturnUrlOrDefault}
          loginRegisterValue={loginRegisterValue}
          countryCode={countryCode}
          authType={authType}
          onLoggedIn={handleUserLoggedIn}
          onEditValue={() => setCurrentStep('emailOrPhone')}
          onLoginWithOTP={() => setCurrentStep('verify')}
          emailOrPhone={loginRegisterValue}
        />
      )}

      {currentStep === 'addPhoneNumber' && (
        <CompleteSignUp
          countryCode={addPhoneCountryCode}
          setCountryCode={setAddPhoneCountryCode}
          value={addedPhoneNumberValue}
          setValue={setAddedPhoneNumberValue}
          email={loginRegisterValue}
          onCompleteSignUp={() => setCurrentStep('addedPhoneNumberVerify')}
        />
      )}

      {currentStep === 'addedPhoneNumberVerify' && (
        <VerifyPhoneNumber
          countryCode={countryCode}
          onEditValue={() => setCurrentStep('addPhoneNumber')}
          value={addedPhoneNumberValue}
          onPhoneNumberVerified={handlePhoneNumberVerified}
        />
      )}
    </>
  );
};
