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 'react-loading-skeleton/dist/skeleton.css'
import i18next from 'i18next'
import { I18nextProvider } from 'react-i18next'
import { QueryCache, QueryClient, QueryClientProvider } from '@tanstack/react-query'
import ToastContainer from './components/Toast'
import FaJson from './langs/fa.json'
import { IApiErrorRepsonse } from './types/error.types'

// Extend Window interface to include isRefreshingToken property
declare global {
  interface Window {
    isRefreshingToken?: boolean;
  }
}
import MainRouter from './router/Main'
import AuthRouter from './router/Auth'
import { Pages } from './config/Pages'
import useConvertNumbers from './hooks/useConvertNumbers';
import { Helmet, HelmetProvider } from 'react-helmet-async';
import moment from 'moment-jalaali';
import { refreshToken } from './pages/auth/service/AuthService';
import { getRefreshToken, getToken, removeRefreshToken, removeToken, setRefreshToken, setToken } from './config/func';

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

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: async (error: IApiErrorRepsonse) => {
      if (error?.response?.status === 401) {
        try {
          // Use a flag to track if refresh is in progress
          if (window.isRefreshingToken) {
            // Wait for the refresh to complete
            await new Promise(resolve => {
              const checkComplete = setInterval(() => {
                if (!window.isRefreshingToken) {
                  clearInterval(checkComplete);
                  resolve(true);
                }
              }, 100);
            });
            return;
          }

          // Set the flag to indicate refresh is in progress
          window.isRefreshingToken = true;

          try {
            const refreshTokenValue = await getRefreshToken();
            const { data } = await refreshToken({ refreshToken: refreshTokenValue || '' });

            if (data?.accessToken?.token) {
              // Save the new token
              await setToken(data?.accessToken?.token);

              // If refresh token also returned, update it
              if (data.refreshToken?.token) {
                await setRefreshToken(data.refreshToken?.token);
              }

              // Retry the failed request
              queryClient.invalidateQueries();
              return;
            } else {
              throw new Error('Invalid token response');
            }
          } finally {
            window.isRefreshingToken = false;
          }
        } catch (refreshError: unknown) {
          console.error('Token refresh failed:', refreshError);
          // Clear tokens and redirect to login
          await removeToken();
          await removeRefreshToken();
          window.location.href = '/auth/login';
        }
      }
    }
  }),
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
      retry: false
      // staleTime: 86400000 // 1 day in milliseconds
    }
  }
});

const App: FC = () => {

  // useNumberFont()
  useConvertNumbers()
  moment.loadPersian({ usePersianDigits: true, dialect: "persian-modern" });

  const [isLogin, setIsLogin] = useState<'checking' | 'isLogin' | 'isNotLogin'>('checking')
  useEffect(() => {
    const checkLogin = async () => {
      const token = await getToken();
      if (token) {
        setIsLogin('isLogin')
      } else {
        setIsLogin('isNotLogin')
        if (window.location.href.split('auth').length === 1) {
          window.location.href = Pages.auth.login
        }
      }
    }
    checkLogin();
  }, []);


  return (
    <BrowserRouter>
      <QueryClientProvider client={queryClient}>
        <I18nextProvider i18n={i18next}>
          <HelmetProvider>
            <Helmet>
              <title>کنسول داناک</title>
            </Helmet>
            {
              isLogin === 'checking' ?
                null
                :
                isLogin === 'isLogin' ?
                  <MainRouter />
                  :
                  <AuthRouter />
            }
          </HelmetProvider>
          <ToastContainer />
        </I18nextProvider>
      </QueryClientProvider>
    </BrowserRouter>
  )
}

export default App