import { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';

import QRCode from './QRCode'
import Authorization from './Authorization'
import SMSCode from './SMSCode'
import Registration from './Registration'
import { authorizeUser } from '../../api-data'
import { asyncLogin } from '../../redux/authorization/operations'
import { format } from '../../helpers'

const AuthPage = () => {
  const [isQR, setIsQR] = useState<boolean>(false)
  const [isCode, setIsCode] = useState<string>('')
  const [isChecked, setIsChecked] = useState<boolean>(true);
  const [isReg, setIsReg] = useState<boolean>(false);
  const [country, setCountry] = useState<string>('Country')
  const [number, setNumber] = useState<string>('')

  const dispatch = useDispatch()

  const handleIsQR = (): void => setIsQR(!isQR)

  const isValidCredentials = () => {
    const numberLength = number.split(' ').join('').trim().length
     if (numberLength < 13 || numberLength > 13) return false
     if (!country || country === 'Country') return false
     if(number.slice(0,1) === '+') return true
      return true
  }

  const handleIsValidCode = async (e: React.ChangeEvent<HTMLInputElement>):Promise<void> => {
    if (isCode && format(e.target.value) === isCode) 
      dispatch(await asyncLogin(number, isCode, () => setIsReg(!isReg)))
    }  

  const handleSendCode = async () => {
      const res = await authorizeUser(format(number), country)
      res && setIsCode(res)
  }

  const handleIsCheck = (e: React.ChangeEvent<HTMLInputElement>): void => {
    const flag = e.target.checked
    setIsChecked(flag);
    localStorage.isChecked = flag
  }

  const handleResetState = ():void => {
    setIsCode('')
    setCountry('Country')
    setNumber('')
  }

  useEffect(() => {
    const isCheckedLC = localStorage.isChecked
    isCheckedLC && setIsChecked(isCheckedLC === 'true'?true:false)
  }, [])
  
  return (
    isReg?<Registration/>:
    isCode ? <SMSCode
      handleIsValidCode={handleIsValidCode}
      number={number}
      handleResetState={handleResetState}/> :
      isQR ? <QRCode handleIsQR={handleIsQR} /> :
        <Authorization handleIsQR={handleIsQR}
          handleSendCode={handleSendCode}
          handleIsCheck={handleIsCheck}
          setNumber={setNumber}
          number={number}
          country={country}
          setCountry={setCountry}
          isChecked={isChecked}
          isValidCredentials={isValidCredentials}/>
  )
};

export default AuthPage;
