'use client'
import React, { createContext, useState, useEffect, ReactNode } from 'react';
import { useIdleTimer } from "react-idle-timer";
import { signOut } 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;
    isUserLoggedIn: boolean;
}

const AutoLogoutProvider: React.FC<AutoLogoutProviderProps> = ({ children, isUserLoggedIn }) => {
    const [lastRequestTime, setLastRequestTime] = useState(Date.now());
    const [logoutInterval, setLogoutInterval] = useState(1); // minute
    const [state, setState] = useState('Active');

    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 (isUserLoggedIn && logoutInterval === 1) {
            //TODO: get auto logout time here
            setLogoutInterval(60);
        }
        else {
            if (!isUserLoggedIn && logoutInterval > 1) {
                setLogoutInterval(1);
            }
        }
    }

    useEffect(() => {
        getLogoutInterval()
        const interval = setInterval(async () => {
            const currentTime = Date.now();
            // if (isPasswordExpiry()) {
            //     navigate('/user/changePassword');
            // }
            if (state !== "Active" && lastActiveTab) {
                const timeElapsed = currentTime - lastRequestTime;
                if (timeElapsed >= logoutInterval * 60 * 1000) {
                    // 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;