import { apiClient } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { acceptStoredPendingInvite } from '@/lib/invitations';
import { createFileRoute, useNavigate } from '@tanstack/react-router';
import { useEffect } from 'react';

function AuthCallbackPage() {
  const navigate = useNavigate();
  const { isAuthenticated } = useAuth();

  useEffect(() => {
    async function handleCallback() {
      if (!isAuthenticated) {
        navigate({ to: '/login' });
        return;
      }

      try {
        await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
        navigate({ to: '/' });
      } catch {
        navigate({ to: '/login' });
      }
    }

    handleCallback();
  }, [isAuthenticated, navigate]);

  return (
    <main className="flex min-h-screen w-full items-center justify-center px-3 sm:px-6">
      <p className="text-sm text-muted-foreground">Completando sesión...</p>
    </main>
  );
}

export const Route = createFileRoute('/auth-callback')({
  component: AuthCallbackPage,
});
