import React, { useState, type JSX } from 'react';
import { LoginRegisterForm } from './LoginRegiserForm';
import type { AuthMode, AuthType } from '../types/auth-types';
import { OtpVerifyForm } from './OtpVerifyForm';
import { isNumeric } from '@/utils/regexes/isNumeric';
import { CompleteSignUp } from './CompleteSignUp';

export const AuthenticationContainer = (): JSX.Element => {
  const [authMode, setAuthMode] = useState<AuthMode>('register');
  const [authType, setAuthType] = useState<AuthType>('phone');
  const [currentStep, setCurrentStep] = useState<
    | 'emailOrPassword'
    | 'verify'
    | 'enterPassword'
    | 'addPhoneNumber'
    | 'addedPhoneNumberVerify'
  >('emailOrPassword');
  const [loginRegisterValue, setLoginRegisterValue] = useState<string>('');
  const [addedPhoneNumberValue, setAddedPhoneNumberValue] =
    useState<string>('');

  const handleLoginRegister = (value: string) => {
    setLoginRegisterValue(value);
    setAuthType(isNumeric(value) ? 'phone' : 'email');
    setCurrentStep('verify');
  };

  const handleOTPVerfied = (otpCode: string) => {
    if (authMode === 'register' && authType === 'email') {
      setAuthType('phone');
      setCurrentStep('addPhoneNumber');
    }
  };

  const handleEditValue = () => {
    setCurrentStep('emailOrPassword');
  };

  const handleCompleteSignUp = (countryCode: string, value: string) => {
    setCurrentStep('addedPhoneNumberVerify');
  };

  const handleCompleteSignUpOTPVerified = (otpCode: string) => {
    console.log(otpCode);
  };

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

  return (
    <>
      {currentStep === 'emailOrPassword' && (
        <LoginRegisterForm
          loginRegisterValue={loginRegisterValue}
          setLoginRegisterValue={setLoginRegisterValue}
          authType={authType}
          setAuthType={setAuthType}
          onLoginRegisterSubmit={handleLoginRegister}
        />
      )}

      {currentStep === 'verify' && (
        <OtpVerifyForm
          onOTPVerified={handleOTPVerfied}
          onEditValue={handleEditValue}
          authMode={authMode}
          authType={authType}
          value={loginRegisterValue}
        />
      )}

      {currentStep === 'addPhoneNumber' && (
        <CompleteSignUp
          value={addedPhoneNumberValue}
          setValue={setAddedPhoneNumberValue}
          email={loginRegisterValue}
          onCompleteSignUp={handleCompleteSignUp}
        />
      )}

      {currentStep === 'addedPhoneNumberVerify' && (
        <OtpVerifyForm
          onOTPVerified={handleCompleteSignUpOTPVerified}
          onEditValue={handleCompleteSignUpEditValue}
          authMode="register"
          authType="phone"
          value={addedPhoneNumberValue}
        />
      )}
    </>
  );
};
