import { FC, useEffect, useState } from 'react'
import { BrowserRouter } from 'react-router-dom'
import 'swiper/swiper-bundle.css';
import 'rc-rate/assets/index.css';
import "quill/dist/quill.snow.css";
import "react-multi-date-picker/styles/layouts/mobile.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 { getRefreshToken, setToken, setRefreshToken, removeToken, removeRefreshToken, getToken } from './config/func';
import { refreshToken } from './pages/auth/service/AuthService';

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

declare global {
  interface Window {
    isRefreshingToken?: boolean;
  }
}

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) {
              await setToken(data?.accessToken?.token);

              if (data.refreshToken?.token) {
                await setRefreshToken(data.refreshToken?.token);
              }

              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 = `${import.meta.env.VITE_LOGIN_URL}?redirect=${window.location.href}`;
        }
      }
    }
  }),
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
      retry: false
      // staleTime: 86400000 // 1 day in milliseconds
    }
  }
});

const App: FC = () => {

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

    const urlParams = new URLSearchParams(window.location.search);
    const workspaceId = urlParams.get('workspaceId');
    if (workspaceId) {
      localStorage.setItem(import.meta.env.VITE_WORKSPACE_ID, workspaceId);
      window.location.href = window.location.pathname
    }

  }, [])

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

export default App