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

import { useLocation } from 'react-router'

import { useMatomo } from '@jonkoops/matomo-tracker-react'

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 { trackPageView } = useMatomo()
  const [isGeoReady, setIsGeoReady] = useState(false)

  useEffect(() => {
    const isProduction = process.env.REACT_APP_ENV === 'production'

    if (isProduction) trackPageView()
  }, [trackPageView, pathname, search])

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