/**
 * Tanflow OAuth Callback Handler
 * Handles the redirect from Tanflow SSO after authentication
 */

import { useEffect, useState, useRef } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { exchangeTanflowCodeForTokens } from '@/services/tanflowAuth';
import { getCurrentUser } from '@/services/authApi';
import { TokenManager } from '@/utils/tokenManager';
import { CheckCircle2, AlertCircle, Loader2 } from 'lucide-react';
import { ReLogo } from '@/assets';

export function TanflowCallback() {
  const { isAuthenticated, isLoading, error, user } = useAuth();
  const [authStep, setAuthStep] = useState<'exchanging' | 'fetching' | 'complete' | 'error'>('exchanging');
  const [errorMessage, setErrorMessage] = useState<string>('');
  const callbackProcessedRef = useRef(false);

  useEffect(() => {
    // Determine current authentication step based on state
    if (error) {
      setAuthStep('error');
      return;
    }
    
    if (isLoading) {
      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');
      // If already authenticated, redirect immediately
      // This handles the case where auth state was set before this component rendered
      setTimeout(() => {
        window.location.href = '/';
      }, 1000);
    }
  }, [isAuthenticated, isLoading, error, user]);

  // Handle Tanflow callback
  useEffect(() => {
    // Only process if we're on the callback route
    if (callbackProcessedRef.current || window.location.pathname !== '/login/callback') {
      return;
    }

    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get('code');
    const errorParam = urlParams.get('error');
    
    // SIMPLIFIED: If no code and no error, it's a logout redirect - redirect immediately
    // Tanflow logout redirects back to /login/callback without any parameters
    if (!code && !errorParam) {
      console.log('🚪 Logout redirect detected: no code, no error - redirecting to home immediately');
      callbackProcessedRef.current = true;
      
      // Redirect to home with logout flags
      const logoutParams = new URLSearchParams();
      logoutParams.set('tanflow_logged_out', 'true');
      logoutParams.set('logout', Date.now().toString());
      const redirectUrl = `/?${logoutParams.toString()}`;
      
      console.log('🚪 Redirecting to:', redirectUrl);
      window.location.replace(redirectUrl);
      return;
    }
    
    // Check if this is a Tanflow callback
    const authProvider = sessionStorage.getItem('auth_provider');
    if (authProvider !== 'tanflow') {
      // Not a Tanflow callback, let AuthContext handle it
      return;
    }

    const handleCallback = async () => {
      callbackProcessedRef.current = true;
      
      const urlParams = new URLSearchParams(window.location.search);
      const code = urlParams.get('code');
      const state = urlParams.get('state');
      const errorParam = urlParams.get('error');

      // Clean URL immediately
      window.history.replaceState({}, document.title, '/login/callback');

      // Check for errors from Tanflow
      if (errorParam) {
        setAuthStep('error');
        sessionStorage.removeItem('auth_provider');
        sessionStorage.removeItem('tanflow_auth_state');
        return;
      }

      // Validate state
      const storedState = sessionStorage.getItem('tanflow_auth_state');
      if (state && state !== storedState) {
        setAuthStep('error');
        sessionStorage.removeItem('auth_provider');
        sessionStorage.removeItem('tanflow_auth_state');
        return;
      }

      if (!code) {
        setAuthStep('error');
        sessionStorage.removeItem('auth_provider');
        sessionStorage.removeItem('tanflow_auth_state');
        return;
      }

      try {
        setAuthStep('exchanging');
        
        // Exchange code for tokens (this stores tokens in TokenManager)
        const tokenData = await exchangeTanflowCodeForTokens(code, state || '');

        // Clear state but keep provider flag for logout detection
        sessionStorage.removeItem('tanflow_auth_state');
        // Keep auth_provider in sessionStorage so logout can detect which provider to use
        // This will be cleared during logout

        setAuthStep('fetching');

        // Fetch user profile (tokenData already has user, but fetch to ensure it's current)
        const userData = tokenData.user || await getCurrentUser();
        
        if (userData) {
          // Store user data in TokenManager (already stored by exchangeTanflowCodeForTokens, but ensure it's set)
          TokenManager.setUserData(userData);
          
          // Show success message briefly
          setAuthStep('complete');
          
          // Clean URL and do full page reload to ensure AuthContext checks auth status
          // This is necessary because AuthContext skips auth check on /login/callback route
          // After reload, AuthContext will check tokens and set isAuthenticated/user properly
          setTimeout(() => {
            window.history.replaceState({}, document.title, '/');
            // Use window.location.href for full page reload to trigger AuthContext initialization
            window.location.href = '/';
          }, 1000);
        } else {
          throw new Error('User data not received');
        }
      } catch (err: any) {
        console.error('Tanflow callback error:', err);
        setAuthStep('error');
        setErrorMessage(err.message || 'Authentication failed');
        sessionStorage.removeItem('auth_provider');
        sessionStorage.removeItem('tanflow_auth_state');
      }
    };

    handleCallback();
  }, []);

  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" />
                <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' && errorMessage && (
            <div className="mt-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
              <p className="text-red-400 text-sm">{errorMessage}</p>
              <button
                onClick={() => {
                  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>
  );
}

