import { RouterProvider } from '@tanstack/react-router';
import { useAtomValue } from 'jotai';
import { Loader2 } from 'lucide-react';
import { useEffect } from 'react';
import { Toaster } from 'sonner';
import '@/index.css';
import { AuthProvider } from '@/modules/auth/contexts/auth-context';
import { authTokenAtom, currentUserDetailsAtom, useValidateToken, setLocaleInClient } from '@/modules/auth/hooks/use-auth-hook';
import { router } from '@/router';
import { getLanguage, SupportedLanguages } from '@/lib/i18n';

declare module '@tanstack/react-router' {
  interface Register {
    router: typeof router;
  }
}

function InnerApp() {
  const token = useAtomValue(authTokenAtom);
  const data = useAtomValue(currentUserDetailsAtom);
  return (
    <RouterProvider
      router={router}
      context={{ token, data }}
    />
  );
}

export default function App() {
  const { isPending, mutate, isSuccess, isError } = useValidateToken();
  const token = useAtomValue(authTokenAtom);

  useEffect(() => {
    const currentLanguage = getLanguage() as SupportedLanguages;
    setLocaleInClient(currentLanguage);
  }, []);

  useEffect(() => {
    if (token) {
      mutate({});
    }
  }, [token, mutate]);

  if (!token || (!isPending && (isError || isSuccess))) {
    return (
      <AuthProvider>
        <Toaster position='top-right' />
        <InnerApp />
      </AuthProvider>
    );
  }
  return (
    <div className='flex h-screen w-screen items-center justify-center'>
      <Loader2 className='h-6 w-6 animate-spin' />
    </div>
  );
}
