import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useDispatch, useSelector } from 'react-redux'
import { actions, selectors } from '../../store'
import { getClientTimezone } from '../../locales'
import { useAuth } from '../../auth'
import { useApi } from '../../api'
import Title from '../Title'
import Policy from '../Policy'
import EmailInput from './EmailInput'
import MainButton from '../MainButton'
import Loader, { LoaderColor } from '../Loader'
import ErrorText from '../ErrorText'
import routes from '../../routes'

function EmailEnterPage(): JSX.Element {
  const api = useApi()
  const { t, i18n } = useTranslation()
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const { user, signUp } = useAuth()
  const { email, birthdate, birthtime } = useSelector(selectors.selectForm)
  const [isDisabled, setIsDisabled] = useState(true)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<Error | null>(null)
  const timezone = getClientTimezone()
  const locale = i18n.language
  const links = [
    { text: 'EULA', href: 'https://aura.wit.life/terms' },
    { text: 'Privacy Policy', href: 'https://aura.wit.life/privacy' },
  ]
  const handleValidEmail = (email: string) => {
    dispatch(actions.form.addEmail(email))
    setIsDisabled(false)
  }
  const handleClick = () => {
    if (user) {
      navigate(routes.client.subscription())
      return
    }
    setError(null)
    setIsLoading(true)
    api.auth({ email, timezone, locale })
      .then(({ auth: { token, user } }) => signUp(token, user))
      .then((token) => {
        const birthday = `${birthdate} ${birthtime}`
        const payload = { user: { profile_attributes: { birthday } }, token }
        return api.updateUser(payload)
      })
      .then(({ user }) => {
        // TODO: remove this when understand btoa issue
        if (user?.profile?.sign?.char) {
          user.profile.sign.char = ''
        }
        dispatch(actions.user.update(user))
      })
      .then(() => navigate(routes.client.subscription()))
      .catch((error: Error) => setError(error))
      .finally(() => setIsLoading(false))
  }


  return (
    <section className='page'>
      <Title variant='h2' className='mt-24'>{t('weWillEmailYou')}</Title>
      <EmailInput
        name="email"
        value={email}
        placeholder={t('yourEmail')}
        onValid={handleValidEmail}
        onInvalid={() => setIsDisabled(true)}
      />
      <p>{t('weDontShare')}</p>
      <Policy links={links} sizing='medium'>{t('continueAgree')}</Policy>
      <MainButton onClick={handleClick} disabled={isDisabled}>
        {isLoading ? <Loader color={LoaderColor.White} /> : t('continue')}
      </MainButton>
      <ErrorText size='medium' isShown={Boolean(error)} message={error?.message} />
    </section>
  )
}

export default EmailEnterPage
