import { apiClient, configureApiClient } from '@/lib/api-client';
import { AuthProvider, useAuth } from '@/lib/auth';
import { queryClient } from '@/lib/query-client';
import { ThemeProvider } from '@/lib/theme';
import { QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { RouterProvider } from '@tanstack/react-router';
import { TanStackRouterDevtools } from '@tanstack/router-devtools';
import { StrictMode, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { router } from './router';
import './index.css';

function AppRouter() {
  const auth = useAuth();

  useEffect(() => {
    router.invalidate();
  }, [auth.isAuthenticated, auth.loading, auth.user]);

  useEffect(() => {
    configureApiClient({
      onForbidden: async () => {
        if (!auth.isAuthenticated) {
          return;
        }

        await auth.signOut();
        await router.navigate({ to: '/login' });
      },
      onError: (error) => {
        console.error('[API]', error);
      },
    });
  }, [auth]);

  if (auth.loading) {
    return (
      <main className="mx-auto flex min-h-screen w-full max-w-6xl items-center justify-center px-6">
        <p className="text-sm text-muted-foreground">Validando sesión...</p>
      </main>
    );
  }

  return (
    <>
      <RouterProvider router={router} context={{ auth, api: apiClient }} />
      {import.meta.env.DEV && <TanStackRouterDevtools router={router} />}
    </>
  );
}

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <ThemeProvider>
      <QueryClientProvider client={queryClient}>
        {import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
        <AuthProvider>
          <AppRouter />
        </AuthProvider>
      </QueryClientProvider>
    </ThemeProvider>
  </StrictMode>
);
