import { useEffect, useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { Auth } from './Auth';
import { AuthCallback } from './AuthCallback';
import { TanflowCallback } from './TanflowCallback';
import { AuthDebugInfo } from '@/components/Auth/AuthDebugInfo';
import { TokenManager } from '@/utils/tokenManager';
import App from '../../App';

export function AuthenticatedApp() {
  const { isAuthenticated, isLoading, error, user, logout } = useAuth();
  const [showDebugInfo, setShowDebugInfo] = useState(false);

  // Check if we're on callback route (after all hooks are called)
  const isCallbackRoute = typeof window !== 'undefined' && 
    window.location.pathname === '/login/callback';

  const handleLogout = async () => {
    try {
      if (!logout) {
        console.error('🔵 ERROR: logout function is undefined!');
        return;
      }
      
      // Call logout from auth context (handles all cleanup and redirect)
      await logout();
    } catch (logoutError) {
      console.error('🔵 Logout error in handleLogout:', logoutError);
      // Even if logout fails, clear local data and redirect
      try {
        localStorage.clear();
        sessionStorage.clear();
        window.location.href = '/';
      } catch (e) {
        console.error('🔵 Error during emergency cleanup:', e);
      }
    }
  };

  useEffect(() => {
    // Auth state changed
  }, [isAuthenticated, isLoading, error, user]);

  // Check for callback parameters
  const urlParams = typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : null;
  const hasCode = urlParams?.get('code');
  const hasError = urlParams?.get('error');

  // Always show callback loader when on callback route (after all hooks)
  // ONLY if it's a real login callback (has code/error) OR if we are still authenticated
  if (isCallbackRoute && (hasCode || hasError || isAuthenticated)) {
    const authProvider = typeof window !== 'undefined' ? sessionStorage.getItem('auth_provider') : null;
    if (authProvider === 'tanflow') {
      return <TanflowCallback />;
    }
    // Default to OKTA callback (or if provider not set yet)
    return <AuthCallback />;
  }

  // Show loading state while checking authentication
  // UNLESS a session supersession is in progress (in which case we want the app UI to stay visible while toast is shown)
  if (isLoading && TokenManager.getAuthError() !== 'SESSION_SUPERSEDED') {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-slate-50 to-slate-100">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-4 border-slate-900 border-t-transparent mx-auto mb-4"></div>
          <p className="text-gray-600">Loading authentication...</p>
        </div>
      </div>
    );
  }

  // Show auth error if present
  if (error) {
    console.error('Authentication Error:', error);
    return (
      <div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-slate-50 to-slate-100">
        <div className="bg-red-50 border border-red-200 text-red-700 px-6 py-4 rounded-lg max-w-md">
          <h3 className="font-semibold mb-2">Authentication Error</h3>
          <p className="text-sm mb-4">{error.message}</p>
          <button
            onClick={() => window.location.reload()}
            className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  // Show login screen if not authenticated
  if (!isAuthenticated) {
    return <Auth />;
  }

  // User is authenticated, show the app
  return (
    <>
      <App onLogout={handleLogout} />
      {showDebugInfo && (
        <AuthDebugInfo isOpen={showDebugInfo} onClose={() => setShowDebugInfo(false)} />
      )}
    </>
  );
}

