import { FC, useEffect, useState } from 'react'
import { BrowserRouter } from 'react-router-dom'
import 'swiper/swiper-bundle.css';
import 'rc-rate/assets/index.css';
import './assets/fonts/roboto/roboto.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'
import useConvertNumbers from './hooks/useConvertNumbers';

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,
      staleTime: 86400000 // 1 day in milliseconds
    },
  },
});

const App: FC = () => {

  // useNumberFont()
  useConvertNumbers()

  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