import { Fragment } from 'react'
import { Redirect } from 'react-router-dom'

import { parse } from 'querystring'
import isObject from 'lodash/isObject'

import { useLocalStore } from 'hooks'

import type { Settings } from 'features/AuthStore/helpers'
import { getClientSettings } from 'features/AuthStore/helpers'
import { T9n } from 'features/T9n'

import { API_ROOT } from '../../config/routes'
import { PAGES } from '../../config/pages'
import { useOauth } from './hooks'
import {
  Header,
  HeaderLogo,
  Content,
  DoneIcon,
  Title,
  Subtitle,
  Form,
  Input,
  SubmitButton,
  Text,
  StyledLink,
  Error,
} from './styled'
import { ErrorPopup } from '../../../../components/ErrorPopup'

const url = `${API_ROOT}/oauth`

const Oauth = () => {
  const {
    response_mode,
    response_type,
    scope,
  } = getClientSettings()

  const [urlParams] = useLocalStore<Partial<Settings>>({
    clearOnUnmount: true,
    defaultValue: {},
    key: 'urlParams',
    validator: isObject,
  })

  const idToken = parse(window.location.hash.replace('#', '')).id_token as string | undefined

  const {
    client_id,
    lang,
    nonce,
    redirect_uri,
    state,
  } = urlParams

  const {
    email,
    error,
    errorAuth,
    formRef,
    handleEmailBlur,
    handleEmailChange,
    handleEmailFocus,
    handleSubmit,
    isOpenErrorPopup,
    setIsOpenErrorPopup,
    showEmailField,
  } = useOauth()

  if (!idToken || !client_id || !redirect_uri) return <Redirect to={PAGES.login} />

  if (showEmailField) {
    return (
      <Fragment>
        <Header>
          <HeaderLogo />
        </Header>
        <Content>
          <DoneIcon />
          <Title>You are one step away from creating inSports account!</Title>
          <Subtitle>Complete the registration form by entering your email:</Subtitle>
          <Form
            ref={formRef}
            onSubmit={handleSubmit}
            method='POST'
            action={url}
          >
            <input
              type='hidden'
              name='client_id'
              defaultValue={client_id}
            />
            <input
              type='hidden'
              name='id_token'
              defaultValue={idToken}
            />
            <input
              type='hidden'
              name='lang'
              defaultValue={lang}
            />
            <input
              type='hidden'
              name='redirect_uri'
              defaultValue={redirect_uri}
            />
            <input
              type='hidden'
              name='response_type'
              defaultValue={response_type}
            />
            <input
              type='hidden'
              name='response_mode'
              defaultValue={response_mode}
            />
            <input
              type='hidden'
              name='scope'
              defaultValue={scope}
            />
            <input
              type='hidden'
              name='state'
              defaultValue={state}
            />
            <input
              type='hidden'
              name='nonce'
              defaultValue={nonce}
            />
            <Input
              autoFocus
              type='email'
              name='email'
              autoComplete='email'
              placeholderLexic='form_email'
              value={email}
              onChange={handleEmailChange}
              onFocus={handleEmailFocus}
              onBlur={handleEmailBlur}
            />
            <SubmitButton
              type='submit'
              disabled={!email}
            >OK
            </SubmitButton>
            {error && (
              <Error>
                <T9n t='error_invalid_email_format' />
              </Error>
            )}
          </Form>
          <Text>
            Also you can use any{' '}
            <StyledLink to={PAGES.login}>other method of authorization</StyledLink>
          </Text>
        </Content>
        <ErrorPopup
          handleModalClose={() => setIsOpenErrorPopup(false)}
          isModalOpen={isOpenErrorPopup}
          error={errorAuth}
        />
      </Fragment>
    )
  }

  return (
    <form
      method='POST'
      ref={formRef}
      action={url}
    >
      <input
        type='hidden'
        name='client_id'
        defaultValue={client_id}
      />
      <input
        type='hidden'
        name='id_token'
        defaultValue={idToken}
      />
      <input
        type='hidden'
        name='lang'
        defaultValue={lang}
      />
      <input
        type='hidden'
        name='redirect_uri'
        defaultValue={redirect_uri}
      />
      <input
        type='hidden'
        name='response_type'
        defaultValue={response_type}
      />
      <input
        type='hidden'
        name='response_mode'
        defaultValue={response_mode}
      />
      <input
        type='hidden'
        name='scope'
        defaultValue={scope}
      />
      <input
        type='hidden'
        name='state'
        defaultValue={state}
      />
      <input
        type='hidden'
        name='nonce'
        defaultValue={nonce}
      />
    </form>
  )
}

export default Oauth
