'use client';
export const dynamic = 'force-dynamic';


import React, { useEffect, useState, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { ProgressSpinner } from 'primereact/progressspinner';

function AuthCallbackContent() {
    const router = useRouter();
    const searchParams = useSearchParams();
    const [status, setStatus] = useState('Traitement de l\'authentification...');

    useEffect(() => {
        const handleAuthCallback = async () => {
            try {
                const code = searchParams.get('code');
                const state = searchParams.get('state');
                const error = searchParams.get('error');

                if (error) {
                    setStatus(`Erreur d'authentification: ${error}`);
                    setTimeout(() => router.push('/auth/login'), 3000);
                    return;
                }

                if (!code) {
                    setStatus('Code d\'autorisation manquant');
                    setTimeout(() => router.push('/auth/login'), 3000);
                    return;
                }

                setStatus('Échange du code d\'autorisation...');

                // Échanger le code contre des tokens
                const response = await fetch('/api/auth/token', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ code, state }),
                });

                if (!response.ok) {
                    throw new Error('Échec de l\'échange de token');
                }

                const tokens = await response.json();
                
                setStatus('Authentification réussie, redirection...');
                
                // Stocker les tokens
                if (tokens.access_token) {
                    localStorage.setItem('accessToken', tokens.access_token);
                    localStorage.setItem('refreshToken', tokens.refresh_token);
                    localStorage.setItem('idToken', tokens.id_token);
                }

                // Rediriger vers le dashboard
                router.push('/dashboard');

            } catch (error) {
                console.error('Erreur lors du traitement de l\'authentification:', error);
                setStatus('Erreur lors de l\'authentification');
                setTimeout(() => router.push('/auth/login'), 3000);
            }
        };

        handleAuthCallback();
    }, [searchParams, router]);

    return (
        <div className="flex flex-column align-items-center justify-content-center min-h-screen">
            <div className="card p-4 text-center">
                <ProgressSpinner style={{ width: '50px', height: '50px' }} />
                <h3 className="mt-3">Authentification en cours</h3>
                <p className="text-600">{status}</p>
            </div>
        </div>
    );
}

const AuthCallbackPage = () => {
    return (
        <Suspense fallback={
            <div className="flex flex-column align-items-center justify-content-center min-h-screen">
                <div className="card p-4 text-center">
                    <ProgressSpinner style={{ width: '50px', height: '50px' }} />
                    <h3 className="mt-3">Chargement...</h3>
                </div>
            </div>
        }>
            <AuthCallbackContent />
        </Suspense>
    );
};

export default AuthCallbackPage;
