'use client'
import React, { createContext, useState, useEffect, ReactNode } from 'react';
import { useIdleTimer } from "react-idle-timer";
import { signOut } from "next-auth/react";
import { useTranslation } from 'react-i18next';
import { useSession } from "next-auth/react";
 
interface TimerContextProps {
    lastRequestTime: number;
    setLastRequestTime: React.Dispatch<React.SetStateAction<number>>;
}
 
export const TimerContext = createContext<TimerContextProps | undefined>(undefined);
 
interface AutoLogoutProviderProps {
    children?: ReactNode;
}
 
const AutoLogoutProvider: React.FC<AutoLogoutProviderProps> = ({ children }) => {
    const { t } = useTranslation("common")
    const [lastRequestTime, setLastRequestTime] = useState(Date.now());
    const [logoutInterval, setLogoutInterval] = useState(1); // minute
    const [state, setState] = useState('Active');
    const { data: session } = useSession();
 
    const onIdle = () => {
        setLastRequestTime(Date.now());
        setState('Idle')
    }
 
    const onActive = () => {
        setLastRequestTime(Date.now());
        setState('Active')
    }
 
    const {
        isLastActiveTab,
    } = useIdleTimer({
        onIdle,
        onActive,
        timeout: 1_000,
        throttle: 500,
        crossTab: true,
        syncTimers: 200,
    })
 
    const lastActiveTab = isLastActiveTab() === null ? 'loading' : isLastActiveTab()
 
    const getLogoutInterval = () => {
        if (session && logoutInterval === 1) {
            //TODO: get auto logout time here
            setLogoutInterval(60);
        }
        else {
            if (!session && logoutInterval > 1) {
                setLogoutInterval(1);
            }
        }
    }
 
    useEffect(() => {
        getLogoutInterval()
        const interval = setInterval(async () => {
            const currentTime = Date.now();
            // if (isPasswordExpiry()) {
            //     navigate('/user/changePassword');
            // }
            // console.log(state)
            // console.log(lastActiveTab)
            if (state !== "Active" && lastActiveTab) {
                const timeElapsed = currentTime - lastRequestTime;
                if (timeElapsed >= logoutInterval * 60 * 1000) {
                    alert(t("Your session has expired, please log in again."))
                    // console.log(timeElapsed / 1000);
                    // console.log(logoutInterval* 60);
                    // console.log(logoutInterval * 60 * 1000 - timeElapsed)
                    signOut()
                }
            }
        }, 1000); // Check every second
 
        return () => {
            clearInterval(interval);
        };
    }, [lastRequestTime, logoutInterval]);
 
 
    return (
        <TimerContext.Provider value={{ lastRequestTime, setLastRequestTime }}>
            {children}
        </TimerContext.Provider>
    );
};
 
export default AutoLogoutProvider;