import { 
    AuthenticationResult, 
    EventType, 
    PublicClientApplication
  } from "@azure/msal-browser";
  import { msalConfig } from "./authConfig";
  import { MsalProvider } from "@azure/msal-react";
  import { ReactNode, useEffect, useState } from "react";
  
  interface AuthProviderProps {
    children: ReactNode;
  }
  
  export const AuthProvider = ({ children }: AuthProviderProps) => {
    const [msalInstance, setMsalInstance] = useState<PublicClientApplication | null>(null);
    const [isInitialized, setIsInitialized] = useState(false);

    
    useEffect(() => {
      const msalApp = new PublicClientApplication(msalConfig);
      
      const initializeMsal = async () => {
        try {
          // Set event handlers first, so we catch all events
          msalApp.addEventCallback((event) => {
            if (event.eventType === EventType.LOGIN_SUCCESS) {
              const payload = event?.payload as AuthenticationResult;
              if (payload?.account) {
                msalApp.setActiveAccount(payload.account);
                console.log("MSAL login successful");
                
                // Store authentication authority for backend communication
                if (payload.account?.environment) {
                  sessionStorage.setItem('auth_authority', payload.account.environment);
                }
                
                console.log('✅ MSAL login successful - tokens will be set in httpOnly cookies by backend');
              }
            } else if (event.eventType === EventType.LOGIN_FAILURE) {
              console.error("MSAL login failed:", event.error);
            }
          });
          
          // Initialize MSAL
          await msalApp.initialize();
          msalApp.enableAccountStorageEvents();
          
          // Handle any redirect response
          const response = await msalApp.handleRedirectPromise();
          if (response) {
            // If we have a response, we've completed a redirect flow
            console.log("MSAL redirect completed successfully");
            if (response.account) {
              msalApp.setActiveAccount(response.account);
              
              // Store authentication authority
              if (response.account.environment) {
                sessionStorage.setItem('auth_authority', response.account.environment);
              }
              
              console.log('✅ MSAL redirect completed - tokens will be set in httpOnly cookies by backend');
            }
          }
          
          // Check for accounts
          const accounts = msalApp.getAllAccounts();
          if (accounts.length > 0) {
            msalApp.setActiveAccount(accounts[0]);
            
            // Store authentication authority for existing accounts
            if (accounts[0].environment) {
              sessionStorage.setItem('auth_authority', accounts[0].environment);
            }
            
            console.log('✅ MSAL account found - tokens will be set in httpOnly cookies by backend');
          }
          
          setMsalInstance(msalApp);
          setIsInitialized(true);
        } catch (err) {
          console.error("MSAL initialization failed", err);
        }
      };
      
      initializeMsal();
    }, []);
    
    if (!isInitialized || !msalInstance) {
      return <div>Loading authentication...</div>;
    }
    
    return <MsalProvider instance={msalInstance}>{children}</MsalProvider>;
  };
  
  export function useAuthProvider() {
    return { AuthProvider };
  }