import { useState, useEffect, useRef } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; import { AuthLayout } from '../components/AuthLayout'; import { AuthButton } from '../components/AuthButton'; import { authApi } from '@/services/api/auth'; import type { ApiError } from '@/schemas/apiSchemas'; export function VerifyEmailPage() { const [searchParams] = useSearchParams(); const navigate = useNavigate(); const [status, setStatus] = useState<'verifying' | 'success' | 'error'>( 'verifying', ); const [message, setMessage] = useState( 'Vérification de votre email en cours...', ); const [loading, setLoading] = useState(false); const [resendLoading, setResendLoading] = useState(false); const [resendCooldown, setResendCooldown] = useState(0); const cooldownIntervalRef = useRef(null); const [token, setToken] = useState(null); // Extraire le token depuis l'URL useEffect(() => { const tokenParam = searchParams.get('token'); if (tokenParam) { setToken(tokenParam); // Vérifier l'email automatiquement si le token est présent handleVerifyEmail(tokenParam); } else { setStatus('error'); setMessage('Lien de vérification invalide ou manquant'); } }, [searchParams]); // Cleanup cooldown interval on unmount useEffect(() => { return () => { if (cooldownIntervalRef.current) { clearInterval(cooldownIntervalRef.current); } }; }, []); // Gérer le cooldown pour le renvoi d'email useEffect(() => { if (resendCooldown > 0) { cooldownIntervalRef.current = setInterval(() => { setResendCooldown((prev) => { if (prev <= 1) { if (cooldownIntervalRef.current) { clearInterval(cooldownIntervalRef.current); } return 0; } return prev - 1; }); }, 1000); } else { if (cooldownIntervalRef.current) { clearInterval(cooldownIntervalRef.current); cooldownIntervalRef.current = null; } } return () => { if (cooldownIntervalRef.current) { clearInterval(cooldownIntervalRef.current); } }; }, [resendCooldown]); // Rediriger vers login après succès useEffect(() => { if (status === 'success') { const timer = setTimeout(() => { navigate('/login', { replace: true }); }, 3000); return () => clearTimeout(timer); } return undefined; }, [status, navigate]); const handleVerifyEmail = async (emailToken: string) => { try { setLoading(true); setStatus('verifying'); setMessage('Vérification de votre email en cours...'); await verifyEmail(emailToken); setStatus('success'); setMessage('Votre email a été vérifié avec succès !'); } catch (error) { setStatus('error'); const apiError = error as ApiError; setMessage(apiError.message || 'La vérification a échoué'); } finally { setLoading(false); } }; const handleResendVerificationEmail = async () => { if (resendCooldown > 0 || resendLoading) { return; } try { setResendLoading(true); // Récupérer l'email depuis localStorage (stocké lors de l'inscription) const email = localStorage.getItem('pendingVerificationEmail'); if (!email) { setMessage( 'Email non trouvé. Veuillez vous réinscrire ou contacter le support.', ); return; } await authApi.resendVerification({ email }); // Définir cooldown de 60 secondes setResendCooldown(60); // Afficher message de confirmation setMessage( 'Email de vérification envoyé ! Veuillez vérifier votre boîte mail.', ); } catch (error) { const apiError = error as ApiError; setMessage(apiError.message || "Échec de l'envoi de l'email"); } finally { setResendLoading(false); } }; // Afficher le statut de vérification if (status === 'verifying') { return (

{message}

Vérification de votre email en cours, veuillez patienter
); } // Afficher le message de succès if (status === 'success') { return (

Succès !

{message}

Vous allez être redirigé vers la page de connexion...

); } // Afficher le message d'erreur avec options de retry/resend return (

Erreur

{message}

{token && ( handleVerifyEmail(token)} loading={loading} type="button" > Réessayer )} 0} type="button" variant="secondary" aria-label={ resendCooldown > 0 ? `Renvoyer l'email de vérification dans ${resendCooldown} secondes` : "Renvoyer l'email de vérification" } > {resendCooldown > 0 ? ( <> Renvoyer dans {resendCooldown} secondes ) : ( "Renvoyer l'email de vérification" )}
); } export default VerifyEmailPage;