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, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import { router } from './router';
import './index.css';

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

  if (auth !== prevAuthRef.current) {
    prevAuthRef.current = auth;
    router.update({ context: { auth, api: apiClient } });
  }

  useEffect(() => {
    router.update({ context: { auth, api: apiClient } });
    router.invalidate();
  }, [auth.isAuthenticated, auth.loading, auth.user]);

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

        await auth.signOut();
        await router.navigate({ to: '/login' });
      },
      onForbidden: async (error) => {
        if (error.message?.includes('verificar tu email')) {
          return;
        }

        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-3 sm: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>
);
