import { type FC, useEffect, useState } from 'react'
import { BrowserRouter } from 'react-router-dom'
import 'swiper/swiper-bundle.css';
// import 'rc-rate/assets/index.css';
import "react-multi-date-picker/styles/layouts/mobile.css"
import 'leaflet/dist/leaflet.css';
import './assets/fonts/irancell/style.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 { type 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;
    isRefreshTokenExpired?: boolean;
  }
}

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: async (error: IApiErrorRepsonse) => {
      if (error?.response?.status === 401) {
        // اگر refresh token منقضی شده باشد، دیگر تلاش نکن
        if (window.isRefreshTokenExpired) {
          return;
        }

        // بررسی کن که آیا خطا از refresh endpoint است
        const isRefreshEndpoint = error?.config?.url?.includes('/admin/auth/refresh');

        // اگر خطا از refresh endpoint است، refresh token منقضی شده
        if (isRefreshEndpoint) {
          window.isRefreshTokenExpired = true;
          await removeToken();
          await removeRefreshToken();
          window.location.href = Pages.auth.login;
          return;
        }

        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();

            if (!refreshTokenValue) {
              window.isRefreshTokenExpired = true;
              await removeToken();
              await removeRefreshToken();
              window.location.href = Pages.auth.login;
              return;
            }

            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);
              }

              // Reset expired flag if refresh was successful
              window.isRefreshTokenExpired = false;

              // 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);

          // بررسی کن که آیا خطا از refresh endpoint است
          const errorWithConfig = refreshError as IApiErrorRepsonse;
          const isRefreshError = errorWithConfig?.config?.url?.includes('/admin/auth/refresh');

          // اگر refresh token خودش 401 خورده، آن را منقضی شده علامت بزن
          if (isRefreshError || errorWithConfig?.response?.status === 401) {
            window.isRefreshTokenExpired = true;
          }

          // Clear tokens and redirect to login
          await removeToken();
          await removeRefreshToken();
          window.location.href = Pages.auth.login;
        }
      }
    }
  }),
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
      retry: false
      // staleTime: 86400000 // 1 day in milliseconds
    }
  }
});

const App: FC = () => {

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

  useEffect(() => {
    // استخراج توکن‌ها از URL در صورت وجود
    const urlParams = new URLSearchParams(window.location.search)
    const tokenFromUrl = urlParams.get('token')
    const refreshTokenFromUrl = urlParams.get('refreshToken')

    if (tokenFromUrl && refreshTokenFromUrl) {
      // ذخیره توکن‌ها (جایگزین کردن توکن‌های قبلی اگر وجود داشته باشند)
      setToken(tokenFromUrl)
      setRefreshToken(refreshTokenFromUrl)

      // حذف پارامترها از URL
      const newUrl = window.location.pathname
      window.history.replaceState({}, '', newUrl)

      // تنظیم وضعیت لاگین و هدایت به صفحه اصلی
      setIsLogin('isLogin')
      if (window.location.pathname === Pages.auth.login) {
        window.location.href = Pages.dashboard
      }
      return
    }

    const token = getToken()
    if (token) {
      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' ?
              <div>loading</div>
              :
              isLogin === 'isLogin' ?
                <MainRouter />
                :
                <AuthRouter />
          }
          <ToastContainer />
        </I18nextProvider>
      </QueryClientProvider>
    </BrowserRouter>
  )
}

export default App