import {
  ReactNode,
  useEffect,
  useState,
} from 'react'

import { useLocation } from 'react-router'

import { getLanguageUrlParam } from 'helpers/languageUrlParam'

import { AuthStore } from 'features/AuthStore'
import { LexicsStore } from 'features/LexicsStore'

import { getGeoInfo } from 'requests'

import { redirectToUrl } from 'helpers'

const initialLanguage = getLanguageUrlParam()

type Props = {
  children: ReactNode,
}

export const GlobalStores = ({ children }: Props) => {
  const { pathname, search } = useLocation()
  const [isGeoReady, setIsGeoReady] = useState(false)

  useEffect(() => {
    (async () => {
      if (pathname === '/' && search === '') {
        const geo = await getGeoInfo()

        if (geo.country_code === 'TN') {
          redirectToUrl('https://diwan.insports.tv')
          return
        }
      }
      setIsGeoReady(true)
    })()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  if (!isGeoReady) return null

  return (
    <LexicsStore initialLanguage={initialLanguage}>
      <AuthStore>
        {children}
      </AuthStore>
    </LexicsStore>
  )
}
