import { useEffect, useRef } 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 { API_ROOT } from '../../config/routes'
import { PAGES } from '../../config/pages'

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 formRef = useRef<HTMLFormElement>(null)

  const idToken = parse(window.location.hash).id_token as string | undefined

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

  useEffect(() => {
    formRef.current?.submit()
  }, [])

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

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

export default Oauth
