import { useEffect, useState } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { AuthService } from '../services/auth.service';

export default function VerifyEmailPage() {
  const [searchParams] = useSearchParams();
  const token = searchParams.get('token');
  const navigate = useNavigate();
  const [status, setStatus] = useState<'LOADING' | 'SUCCESS' | 'ERROR'>('LOADING');
  const [message, setMessage] = useState('');

  useEffect(() => {
    if (!token) {
      setStatus('ERROR');
      setMessage('Token no proporcionado');
      return;
    }

    AuthService.verifyEmail(token)
      .then(() => {
        setStatus('SUCCESS');
        setTimeout(() => navigate('/'), 3000); // Redirigir al home
      })
      .catch((err) => {
        setStatus('ERROR');
        setMessage(err.response?.data?.message || 'Error al verificar email');
      });
  }, [token, navigate]);

  return (
    <div className="min-h-screen flex items-center justify-center p-6">
      <div className="glass p-10 rounded-[2.5rem] border border-white/10 text-center max-w-md w-full shadow-2xl">
        {status === 'LOADING' && (
          <>
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto mb-6"></div>
            <h2 className="text-2xl font-black uppercase tracking-tighter">Verificando...</h2>
          </>
        )}
        {status === 'SUCCESS' && (
          <>
            <div className="text-5xl mb-6">✅</div>
            <h2 className="text-2xl font-black uppercase tracking-tighter text-green-400 mb-2">¡Cuenta Activada!</h2>
            <p className="text-gray-400 text-sm">Ya puedes iniciar sesión. Redirigiendo...</p>
          </>
        )}
        {status === 'ERROR' && (
          <>
            <div className="text-5xl mb-6">❌</div>
            <h2 className="text-2xl font-black uppercase tracking-tighter text-red-400 mb-2">Error</h2>
            <p className="text-gray-400 text-sm">{message}</p>
            <button onClick={() => navigate('/')} className="mt-6 text-blue-400 font-bold uppercase text-xs tracking-widest">Ir al inicio</button>
          </>
        )}
      </div>
    </div>
  );
}