import React, { createContext, useState, useEffect, useRef } from 'react';
import {useNavigate} from "react-router-dom";
import {useIdleTimer} from "react-idle-timer";
import { handleLogoutFunction } from 'auth/index';
import { useDispatch } from "react-redux";
import { useIntl } from "react-intl";
import { 
    isUserLoggedIn, 
    isGLDLoggedIn,
    isPasswordExpiry
} from "utils/Utils";

const TimerContext = createContext();

const AutoLogoutProvider = ({ children }) => {
    const intl = useIntl();
    const [lastRequestTime, setLastRequestTime] = useState(Date.now());
    const navigate = useNavigate();
    const [logoutInterval, setLogoutInterval] = useState(1);
    const idleLogoutTriggeredRef = useRef(false);
    // const [remainingInterval] = useState(5);
    const [state, setState] = useState('Active');
    const dispatch = useDispatch()

    const onIdle = () => {
        setLastRequestTime(Date.now());
        setState('Idle')
    }

    const onActive = () => {
        setLastRequestTime(Date.now());
        setState('Active')
    }

    const {
        // getRemainingTime,
        //getTabId,
        isLastActiveTab,
    } = useIdleTimer({
        onIdle,
        onActive,
        timeout: 1_000,
        throttle: 500,
        crossTab: true,
        syncTimers: 200,
    })

    const lastActiveTab = isLastActiveTab() === null ? 'loading' : isLastActiveTab()
    //const tabId = getTabId() === null ? 'loading' : getTabId().toString()

    const getLogoutInterval = () =>{
        if(isUserLoggedIn()&&logoutInterval===1){
            //TODO: get auto logout time here
            if(isGLDLoggedIn()){
                setLogoutInterval(240);
                // console.log("Set Logout Interval: 240")
            }else{
                setLogoutInterval(60);
                // console.log("Set Logout Interval: 60")
            }
            // axios.get(`${apiPath}${GET_IDLE_LOGOUT_TIME}`,
            // )
            // .then((response) => {
            //     if (response.status === 200) {
            //         setLastRequestTime(Date.now());
            //         setLogoutInterval(parseInt(response.data.data));
            //     }
            // })
            // .catch(error => {
            //     console.log(error);
            //     return false;
            // });
        }
        else{
            if(!isUserLoggedIn()&&logoutInterval>1){
                setLogoutInterval(1);
            }
            //navigate('/login');
        }
    }

    useEffect(() => {
        getLogoutInterval()
        // console.log("AutoLogoutProvider Start")
        // console.log(logoutInterval)
        const interval = setInterval(async () => {
            const currentTime = Date.now();
            if (isPasswordExpiry()){
                navigate('/user/changePassword');
            }
            // getRemainingTime();
            if(state !== "Active" && lastActiveTab){
                const timeElapsed = currentTime - lastRequestTime;
                // console.log(parseInt(timeElapsed/1000));
                // console.log(logoutInterval* 60);
                // console.log(remainingInterval * 60);
                // console.log(logoutInterval * 60 * 1000 - timeElapsed)
                if (timeElapsed >= logoutInterval * 60 * 1000) {
                    if (isUserLoggedIn() && !idleLogoutTriggeredRef.current) {
                        idleLogoutTriggeredRef.current = true;
                        // Skip alert if token-expiry (axios 401) already showed one, to avoid duplicate alerts
                        if (localStorage.getItem("expiredAlertShown") === null) {
                            localStorage.setItem("expiredAlertShown", "true");
                            alert(intl.formatMessage({ id: "autoLogout" }));
                        }
                        dispatch(handleLogoutFunction());
                        navigate('/login');
                        window.location.reload();
                    }
                }
            }
            // else if(state === "Active"){
            //     const timeElapsed = currentTime - lastRequestTime;
            //     if ( (logoutInterval * 60 * 1000 - timeElapsed) <= remainingInterval * 60 * 1000){

            //     }
            //     //TODO: if is active and remaining time < 5 min then refresh token
            // }
        }, 1000); // Check every second

        return () => {
            clearInterval(interval);
        };
    }, [lastRequestTime,logoutInterval]);


    return (
        <TimerContext.Provider value={{lastRequestTime,setLastRequestTime}}>
            {children}
        </TimerContext.Provider>
    );
};

export { TimerContext, AutoLogoutProvider };