import {
  Suspense,
  useEffect,
  useState,
} from 'react'
import { Router } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from 'react-query'
import { ReactQueryDevtools } from 'react-query/devtools'

import { history } from 'config/history'
import { client } from 'config/clients'
import { isAvailable } from 'config/env'

import { readToken } from 'helpers'

import { isLocalhost } from 'serviceWorker'

import { setClientTitleAndDescription } from 'helpers/setClientHeads'

import { GlobalStores } from 'features/GlobalStores'
import { Background } from 'features/Background'
import { GlobalStyles } from 'features/GlobalStyles'
import { Theme } from 'features/Theme'

import { UnavailableText } from 'components/UnavailableText'

import { AuthenticatedApp } from './AuthenticatedApp'
import { useAuthStore } from '../AuthStore'

setClientTitleAndDescription(client.title, client.description)

const Main = () => {
  const [isToken, setIsToken] = useState(false)
  const { userInfo } = useAuthStore()
  const queryClient = new QueryClient()

  useEffect(() => {
    readToken() && setIsToken(true)
  }, [userInfo])

  // имеется действующий токен
  return isToken ? (
    <QueryClientProvider client={queryClient}>
      <ReactQueryDevtools initialIsOpen={isLocalhost} />
      <AuthenticatedApp />
    </QueryClientProvider>
  ) : null
}

const date = new Date()
const startDate = '2022-11-24T23:00:00'
const stopDate = '2022-11-25T05:00:00'

const OTTApp = () => (
  <Router history={history}>
    <Theme>
      <GlobalStyles />
      <GlobalStores>
        <Background>
          <Suspense fallback={null}>
            {isAvailable
                && (date.getTime() < new Date(startDate).getTime()
                    || date.getTime() > new Date(stopDate).getTime())
              ? (<Main />) : (<UnavailableText />)}
          </Suspense>
        </Background>
      </GlobalStores>
    </Theme>
  </Router>
)

export default OTTApp
