import React, { useEffect, useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { Auth } from './Auth';
import { AuthCallback } from './AuthCallback';
import { AuthDebugInfo } from '@/components/Auth/AuthDebugInfo';
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 () => {
    console.log('🔵 ========================================');
    console.log('🔵 AuthenticatedApp.handleLogout - CALLED');
    console.log('🔵 Timestamp:', new Date().toISOString());
    console.log('🔵 logout function exists?', !!logout);
    console.log('🔵 ========================================');
    
    try {
      if (!logout) {
        console.error('🔵 ERROR: logout function is undefined!');
        return;
      }
      
      console.log('🔵 Calling logout from auth context...');
      // Call logout from auth context (handles all cleanup and redirect)
      await logout();
      console.log('🔵 Logout successful - redirecting to login...');
    } catch (logoutError) {
      console.error('🔵 Logout error in handleLogout:', logoutError);
      // Even if logout fails, clear local data and redirect
      try {
        console.log('🔵 Attempting emergency cleanup...');
        localStorage.clear();
        sessionStorage.clear();
        window.location.href = '/';
      } catch (e) {
        console.error('🔵 Error during emergency cleanup:', e);
      }
    }
  };

  useEffect(() => {
    console.log('AuthenticatedApp - Auth State Changed:', {
      isAuthenticated,
      isLoading,
      error: error?.message,
      hasUser: !!user,
      timestamp: new Date().toISOString()
    });

    if (user) {
      console.log('========================================');
      console.log('USER AUTHENTICATED - Full Details');
      console.log('========================================');
      console.log('User ID:', user.userId || user.sub);
      console.log('Employee ID:', user.employeeId);
      console.log('Email:', user.email);
      console.log('Name:', user.displayName || user.name);
      console.log('Display Name:', user.displayName);
      console.log('First Name:', user.firstName);
      console.log('Last Name:', user.lastName);
      console.log('Department:', user.department);
      console.log('Designation:', user.designation);
      console.log('Is Admin:', user.isAdmin);
      console.log('========================================');
      console.log('ALL USER DATA:');
      console.log(JSON.stringify(user, null, 2));
      console.log('========================================');
    }
  }, [isAuthenticated, isLoading, error, user]);

  // Always show callback loader when on callback route (after all hooks)
  if (isCallbackRoute) {
    return <AuthCallback />;
  }

  // Show loading state while checking authentication
  if (isLoading) {
    console.log('Auth0 is still loading...');
    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) {
    console.log('User not authenticated, showing login screen');
    return <Auth />;
  }

  // User is authenticated, show the app
  console.log('User authenticated successfully, showing main application');
  return (
    <>
      <App onLogout={handleLogout} />
      {showDebugInfo && (
        <AuthDebugInfo isOpen={showDebugInfo} onClose={() => setShowDebugInfo(false)} />
      )}
    </>
  );
}

