import React, { createContext, useState, useEffect } from 'react';
import {handleLogoutFunction} from "../auth";
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 AutoLogoutProvider = ({ children }) => {
    const [lastRequestTime, setLastRequestTime] = useState(Date.now());
    const navigate = useNavigate();
    const [logoutInterval, setLogoutInterval] = useState(30);
    const [state, setState] = useState('Active');

    const [isTempWindowOpen, setIsTempWindowOpen] = useState(false);
    const [forceChangePassword, setForceChangePassword] = useState(false);

    useEffect(() => {
        const userData = getUserData();
        const checked = localStorage.getItem("checkPasswordExpired");
        if(userData !== null){
            //system user
            if(checked === "false"){
                axios.get(`${apiPath}${GET_USER_PASSWORD_DURATION}`,{
                    params:{
                        id: userData.id
                    }
                })
                    .then((response) => {
                        if (response.status === 200) {
                            setForceChangePassword(response.data.expired);
                            if(!response.data.expired){
                                localStorage.setItem("checkPasswordExpired",true);
                            }
                        }
                    })
                    .catch(error => {
                        console.log(error);
                        return false;
                    });
            }
        }
    }, []);

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

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

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

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

    useEffect(() => {
        const userData = getUserData();
        if(!isObjEmpty(userData)){
            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{
            //navigate('/login');
        }
    }, []);

    useEffect(() => {
        const interval = setInterval(async () => {
            const currentTime = Date.now();
            getRemainingTime();
            if(state !== "Active" && lastActiveTab){
                const timeElapsed = currentTime - lastRequestTime;
                // if (timeElapsed >= logoutInterval * 60 * 1000) {
                //     await dispatch(handleLogoutFunction());
                //     await navigate('/login');
                //     await window.location.reload();
                // }
            }
        }, 1000); // Check every second

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

    useEffect(() => {
        //if user data from parent are not null
        if(forceChangePassword){
            setIsTempWindowOpen(true);
        }
    }, [forceChangePassword]);

    const handleTempClose = (event, reason) => {
        if (reason && reason === "backdropClick")
            return;
        setIsTempWindowOpen(false);
    };

    return (
        <TimerContext.Provider value={{lastRequestTime,setLastRequestTime}}>
            {children}
            <ThemeProvider theme={LIONER_FORM_THEME}>
                <ChangePasswordWindow
                    isWindowOpen={isTempWindowOpen}
                    title={"Change Password"}
                    onNormalClose={handleTempClose}
                    onConfirmClose={handleTempClose}
                    isForce={true}
                />
            </ThemeProvider>
        </TimerContext.Provider>
    );
};

export { TimerContext, AutoLogoutProvider };