import { useEffect, useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { CheckCircle2, AlertCircle, Loader2 } from 'lucide-react';
import { ReLogo } from '@/assets';

export function AuthCallback() {
  const { isAuthenticated, isLoading, error, user } = useAuth();
  const [authStep, setAuthStep] = useState<'exchanging' | 'fetching' | 'complete' | 'error'>('exchanging');

  useEffect(() => {
    // Determine current authentication step based on state
    if (error) {
      setAuthStep('error');
      return;
    }
    
    if (isLoading) {
      // If we have code in URL but no user yet, we're exchanging
      const urlParams = new URLSearchParams(window.location.search);
      const hasCode = urlParams.get('code');
      
      if (hasCode && !user) {
        setAuthStep('exchanging');
      } else if (user && !isAuthenticated) {
        setAuthStep('fetching');
      } else {
        setAuthStep('exchanging');
      }
    } else if (user && isAuthenticated) {
      setAuthStep('complete');
      // AuthContext already handles the URL change via replaceState
      // No need to do a full page reload which would lose React state
      // The AuthenticatedApp will re-render and show the App component
    }
  }, [isAuthenticated, isLoading, error, user]);

  // Get dynamic loading message
  const getLoadingMessage = () => {
    switch (authStep) {
      case 'exchanging':
        return 'Exchanging authorization code...';
      case 'fetching':
        return 'Fetching your profile...';
      case 'complete':
        return 'Authentication successful!';
      case 'error':
        return 'Authentication failed';
      default:
        return 'Completing authentication...';
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900">
      <div className="absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiMxZTIxMmQiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMzAiLz48L2c+PC9nPjwvc3ZnPg==')] opacity-20"></div>
      
      <div className="relative z-10 text-center px-4 max-w-md w-full">
        {/* Logo/Brand Section */}
        <div className="mb-8">
          <div className="flex flex-col items-center justify-center">
            <img 
              src={ReLogo} 
              alt="Royal Enfield Logo" 
              className="h-10 w-auto max-w-[168px] object-contain mb-2"
            />
            <p className="text-xs text-gray-400 text-center truncate">Approval Portal</p>
          </div>
        </div>

        {/* Main Loader Card */}
        <div className="bg-white/10 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/20">
          {/* Status Icon */}
          <div className="mb-6 flex justify-center">
            {authStep === 'error' ? (
              <div className="relative">
                <div className="absolute inset-0 animate-ping opacity-75">
                  <AlertCircle className="w-16 h-16 text-red-500" />
                </div>
                <AlertCircle className="w-16 h-16 text-red-500 relative" />
              </div>
            ) : authStep === 'complete' ? (
              <div className="relative">
                <div className="absolute inset-0 animate-ping opacity-75">
                  <CheckCircle2 className="w-16 h-16 text-green-500" />
                </div>
                <CheckCircle2 className="w-16 h-16 text-green-500 relative" />
              </div>
            ) : (
              <div className="relative">
                <Loader2 className="w-16 h-16 animate-spin text-re-red" />
                {/* Outer rotating ring */}
                <div className="absolute inset-0 border-4 rounded-full border-re-red/20"></div>
                <div className="absolute inset-0 border-4 border-transparent border-t-re-red rounded-full animate-spin"></div>
              </div>
            )}
          </div>

          {/* Loading Message */}
          <div className="mb-6">
            <h2 className="text-xl font-semibold text-white mb-2">
              {authStep === 'complete' ? 'Welcome Back!' : authStep === 'error' ? 'Authentication Error' : 'Authenticating'}
            </h2>
            <p className="text-slate-300 text-sm">{getLoadingMessage()}</p>
          </div>

          {/* Progress Steps */}
          {authStep !== 'error' && (
            <div className="space-y-3 mb-6">
              <div className={`flex items-center gap-3 text-sm transition-all duration-500 ${authStep === 'exchanging' ? 'text-white' : 'text-slate-400'}`}>
                <div className={`w-2 h-2 rounded-full transition-all duration-500 ${authStep === 'exchanging' ? 'bg-re-red animate-pulse' : 'bg-slate-600'}`}></div>
                <span>Validating credentials</span>
              </div>
              <div className={`flex items-center gap-3 text-sm transition-all duration-500 ${authStep === 'fetching' ? 'text-white' : 'text-slate-400'}`}>
                <div className={`w-2 h-2 rounded-full transition-all duration-500 ${authStep === 'fetching' ? 'bg-re-red animate-pulse' : 'bg-slate-600'}`}></div>
                <span>Loading your profile</span>
              </div>
              {authStep === 'complete' && (
                <div className="flex items-center gap-3 text-sm transition-all duration-500 text-white">
                  <div className="w-2 h-2 rounded-full transition-all duration-500 bg-green-500"></div>
                  <span>Setting up your session</span>
                </div>
              )}
            </div>
          )}

          {/* Error Message */}
          {authStep === 'error' && error && (
            <div className="mt-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
              <p className="text-red-400 text-sm">{error.message || 'An error occurred during authentication'}</p>
              <button
                onClick={() => {
                  // Use window.location instead of navigate since Router context isn't available yet
                  window.location.href = '/';
                }}
                className="mt-4 text-sm text-red-400 hover:text-red-300 underline"
              >
                Return to login
              </button>
            </div>
          )}

          {/* Animated Progress Bar */}
          {authStep !== 'error' && authStep !== 'complete' && (
            <div className="mt-6">
              <div className="h-1.5 bg-slate-700/50 rounded-full overflow-hidden">
                <div 
                  className="h-full bg-re-red rounded-full animate-pulse"
                  style={{
                    animation: 'progress 2s ease-in-out infinite',
                  }}
                ></div>
              </div>
              <style>{`
                @keyframes progress {
                  0%, 100% { width: 20%; }
                  50% { width: 80%; }
                }
              `}</style>
            </div>
          )}
        </div>

        {/* Footer Text */}
        <p className="mt-6 text-slate-500 text-xs">
          {authStep === 'complete' ? 'Loading dashboard...' : 'Please wait while we secure your session'}
        </p>
      </div>

      {/* Animated Background Elements */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute top-1/4 left-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse"></div>
        <div className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse delay-1000"></div>
      </div>
    </div>
  );
}
