import React, { createContext, useState, useEffect, useRef, useCallback} from 'react';
import { useMsal, useIsAuthenticated } from "@azure/msal-react";
import { InteractionRequiredAuthError } from "@azure/msal-browser";
import {handleLogoutFunction} from "../auth";
import { useDispatch } from 'react-redux';
import {dispatch} from "../store";
import {useNavigate} from "react-router-dom";
import axios from "axios";
import {apiPath, getUserData} from "../auth/utils";
import {GET_IDLE_LOGOUT_TIME, GET_USER_PASSWORD_DURATION} from "../utils/ApiPathConst";
import {isObjEmpty} from "../utils/Utils";
import {useIdleTimer} from "react-idle-timer";
import {LIONER_FORM_THEME} from "../themes/themeConst";
import {ChangePasswordWindow} from "../layout/MainLayout/Header/HeaderContent/Profile/ChangePasswordWindow";
import {ThemeProvider} from "@emotion/react";

const TimerContext = createContext();
const IDLE_TIMEOUT_SECONDS = 3600;

const AutoLogoutProvider = ({ children }) => {
    const dispatch = useDispatch();
    // ⚡️ Use the inProgress property from useMsal to guard against premature logout
    const { instance, accounts, inProgress } = useMsal(); 
    
    const isAuthenticated = accounts.length > 0;
    const idleTimerRef = useRef(null);
    
    // The core logout logic
    const forceLogout = useCallback(() => {
        
        // 🛑 CRITICAL GUARD CLAUSE:
        // Do NOT log out if:
        // 1. MSAL is currently busy (acquiring token, handling redirect, etc.)
        // 2. No accounts are logged in (to prevent unnecessary calls)
        if (inProgress !== "none" || !isAuthenticated) {
            console.log("MSAL is busy or user is not authenticated. Aborting idle logout attempt.");
            return; 
        }

        console.warn('Idle timeout reached. Forcing logout.');

        // 1. Clear Redux/local storage state
        dispatch(handleLogoutFunction());
        
        // 2. Perform MSAL logout (This is what triggers the Azure AD sign out page)
        instance.logoutRedirect();
        
    }, [dispatch, instance, isAuthenticated, inProgress]); // Dependencies updated

    // useEffect for monitoring activity and setting up the timer
    useEffect(() => {
        console.log('AutoLogoutProvider Render/Effect:', {
            isAuthenticated,
            inProgress,
            hasAccessToken: !!localStorage.getItem('accessToken') // Check legacy token
        });
        // ... (Your existing logic to set up the idle timer and reset it on activity)
        // Ensure that your timer starts ONLY if isAuthenticated is true AND inProgress is "none"

        if (isAuthenticated && inProgress === "none") {
            // Start the timer
            idleTimerRef.current = setTimeout(forceLogout, IDLE_TIMEOUT_SECONDS * 1000);
        }

        return () => {
            clearTimeout(idleTimerRef.current);
        };
    }, [isAuthenticated, inProgress, forceLogout]); // Depend on MSAL state

    return children;
};

export { TimerContext, AutoLogoutProvider };