/* eslint-disable @typescript-eslint/no-unused-vars */
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 { ErrorBoundary } from 'components/ErrorBoundary'

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

setClientTitleAndDescription(client.title, client.description)

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

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

  // отправляем идентификаторы пользователей в гугл аналитику
  useEffect(() => {
    if (user) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (window as any)?.dataLayer.push({
        event: 'userData',
        userId: user.profile?.sub,
      })
    }
  }, [user])

  // имеется действующий токен
  return isToken ? (
    <ErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <ReactQueryDevtools initialIsOpen={isLocalhost} />
        <AuthenticatedApp />
      </QueryClientProvider>
    </ErrorBoundary>
  ) : 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 />)} */}
            <UnavailableText />
          </Suspense>
        </Background>
      </GlobalStores>
    </Theme>
  </Router>
)

export default OTTApp
