import { useEffect, useRef } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';

export default function LoginSuccess() {
    const navigate = useNavigate();
    const [searchParams] = useSearchParams();
    const { loginWithOAuth } = useAuth();
    const hasProcessed = useRef(false);

    useEffect(() => {
        if (hasProcessed.current) return;

        const token = searchParams.get('token');
        const userParam = searchParams.get('user');

        

        if (token && userParam) {
            try {
                hasProcessed.current = true;
                
                const userData = JSON.parse(decodeURIComponent(userParam));
                
                
                loginWithOAuth(userData, token);
                
                setTimeout(() => {
                    navigate('/', { replace: true });
                }, 100);
                
            } catch (error) {
                console.error('Error processing OAuth login:', error);
                hasProcessed.current = true;
                setTimeout(() => {
                    navigate('/login?error=invalid_data', { replace: true });
                }, 100);
            }
        } else {
            
            hasProcessed.current = true;
            setTimeout(() => {
                navigate('/login?error=missing_data', { replace: true });
            }, 100);
        }
    }, []);

    return (
        <div className="min-h-screen flex items-center justify-center bg-gray-50">
            <div className="text-center">
                <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-500 mx-auto"></div>
                <p className="mt-4 text-gray-600">Finalisation de la connexion...</p>
            </div>
        </div>
    );
}
