import { FC, useEffect, useState } from 'react'
import { BrowserRouter } from 'react-router-dom'
import 'swiper/swiper-bundle.css';
import 'rc-rate/assets/index.css';
import i18next from 'i18next'
import { I18nextProvider } from 'react-i18next'
import { QueryCache, QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ToastContainer } from 'react-toastify'
import FaJson from './langs/fa.json'
import { IApiErrorRepsonse } from './types/error.types'
import MainRouter from './router/Main'
import AuthRouter from './router/Auth'
import { Pages } from './config/Pages'

i18next.init({
  interpolation: { escapeValue: false },
  lng: 'fa',
  resources: {
    fa: {
      global: FaJson
    }
  }
})

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: (error: IApiErrorRepsonse) => {
      if (error?.response?.status === 401) {
        localStorage.removeItem(import.meta.env.VITE_TOKEN_NAME)
        window.location.href = '/auth/login';
      }
    },
  }),
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
    },
  },
});

const App: FC = () => {

  const [isLogin, setIsLogin] = useState<'checking' | 'isLogin' | 'isNotLogin'>('checking')
  useEffect(() => {

    if (localStorage.getItem(import.meta.env.VITE_TOKEN_NAME)) {
      setIsLogin('isLogin')
    } else {
      setIsLogin('isNotLogin')
      if (window.location.href.split('auth').length === 1) {
        window.location.href = Pages.auth.login
      }
    }

  }, [])




  return (
    <BrowserRouter>
      <QueryClientProvider client={queryClient}>
        <I18nextProvider i18n={i18next}>
          {
            isLogin === 'checking' ?
              null
              :
              isLogin === 'isLogin' ?
                <MainRouter />
                :
                <AuthRouter />
          }
          <ToastContainer />
        </I18nextProvider>
      </QueryClientProvider>
    </BrowserRouter>
  )
}

export default App