import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Loader2, CheckCircle, XCircle } from 'lucide-react';

export default function AuthCallback() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading');
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const accessToken = searchParams.get('accessToken');
    const refreshToken = searchParams.get('refreshToken');
    const isNewUser = searchParams.get('isNewUser') === 'true';
    const errorParam = searchParams.get('error');
    const returnUrl = searchParams.get('returnUrl') || '/dashboard';

    if (errorParam) {
      setStatus('error');
      setError(getErrorMessage(errorParam));
      return;
    }

    if (accessToken && refreshToken) {
      // Store tokens
      localStorage.setItem('accessToken', accessToken);
      localStorage.setItem('refreshToken', refreshToken);

      setStatus('success');

      // Redirect after a brief delay
      setTimeout(() => {
        if (isNewUser) {
          // New user - redirect to dashboard (onboarding not yet implemented)
          navigate('/dashboard');
        } else {
          navigate(returnUrl);
        }
      }, 1500);
    } else {
      setStatus('error');
      setError('No se recibieron los tokens de autenticacion');
    }
  }, [searchParams, navigate]);

  const getErrorMessage = (errorCode: string): string => {
    const messages: Record<string, string> = {
      invalid_state: 'La sesion ha expirado. Por favor intenta de nuevo.',
      oauth_failed: 'Error al conectar con el proveedor. Por favor intenta de nuevo.',
      oauth_error: 'Ocurrio un error durante la autenticacion.',
      missing_code_verifier: 'Error de configuracion. Por favor intenta de nuevo.',
      invalid_provider: 'Proveedor de autenticacion no valido.',
    };
    return messages[errorCode] || 'Error desconocido durante la autenticacion.';
  };

  if (status === 'loading') {
    return (
      <div className="min-h-screen bg-gray-950 flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-12 h-12 text-primary-500 animate-spin mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-white mb-2">Completando autenticacion...</h2>
          <p className="text-gray-400">Por favor espera un momento</p>
        </div>
      </div>
    );
  }

  if (status === 'success') {
    return (
      <div className="min-h-screen bg-gray-950 flex items-center justify-center">
        <div className="text-center">
          <CheckCircle className="w-16 h-16 text-green-500 mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-white mb-2">Autenticacion exitosa!</h2>
          <p className="text-gray-400">Redirigiendo...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-950 flex items-center justify-center">
      <div className="text-center max-w-md mx-auto px-4">
        <XCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
        <h2 className="text-xl font-semibold text-white mb-2">Error de autenticacion</h2>
        <p className="text-gray-400 mb-6">{error}</p>
        <button
          onClick={() => navigate('/login')}
          className="btn btn-primary"
        >
          Volver a Iniciar Sesion
        </button>
      </div>
    </div>
  );
}
