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'

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()

  useEffect(() => {
    const isCheckedLC = localStorage.isChecked
    isCheckedLC && setIsChecked(isCheckedLC === 'true'?true:false)
  }, [])

  const format = (a: string) => a.split(' ').join('').trim()

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

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

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

  const handleResetState = ():void => {
    setIsCode('')
    setCountry('Country')
    setNumber('')
  }
 
  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} />
  )
};

export default AuthPage;
