'use client'
import { createContext, useEffect, useRef, useCallback, ReactNode } from 'react';
import { useSession } from "next-auth/react";
// import { useTranslation } from 'react-i18next';
import { SessionWithTokens } from '@/config/authConfig';
import { fetchTokenDetails } from '@/app/api/token/actions';

interface RefreshTokenContextProps {

}

export const RefreshTokenContext = createContext<RefreshTokenContextProps | undefined>(undefined);

interface RefreshTokenProviderProps {
    children?: ReactNode;
}

const RefreshTokenProvider: React.FC<RefreshTokenProviderProps> = ({ children }) => {
    const { data, update } = useSession();
    const session = useRef(data as SessionWithTokens)
    // const token = useRef<string | null>(session.current?.accessToken ?? null)
    const isRefresh = useRef<boolean>(false)

    const handleRefreshToken = useCallback(async () => {
        if (!isRefresh.current) {
            const refreshToken = session.current.refreshToken ?? ""

            isRefresh.current = true

            try {
                const response = await fetchTokenDetails({ refreshToken: refreshToken })

                if (response) {
                    const newAccessToken = response.accessToken
                    const newRefreshToken = response.refreshToken

                    await update({
                        accessToken: newAccessToken,
                        refreshToken: newRefreshToken
                    })

                    // console.log("New Access Token: ", newAccessToken)
                    // console.log("%c [ Old Refresh Token ]:", 'font-size:13px; background:pink; color:#bf2c9f;', `${refreshToken}`)
                    // console.log("%c [ New Refresh Token ]:", 'font-size:13px; background:pink; color:#bf2c9f;', `${newRefreshToken}`)

                }

                isRefresh.current = false
            } catch (refreshError) {
                console.log('Failed to refresh token');
                console.log(refreshError);
                isRefresh.current = false;
            };
        }
    }, [session.current, update])

    const checkTokenExpiry = useCallback(() => {
        const accessToken = session.current.accessToken
        if (accessToken) {
            const tokenExp = JSON.parse(atob(accessToken.split('.')[1])).exp;
            const currentTime = Math.floor(Date.now() / 1000);
            const expiryTime = tokenExp - 30; // Refresh 30 seconds before expiry

            // console.log("%c [ Expiry Time ]:", 'font-size:13px; background:pink; color:#bf2c9f;', `${new Date(expiryTime * 1000).toLocaleString()}`)

            if (currentTime >= expiryTime) {
                if (session.current) {
                    handleRefreshToken();
                }
            }
        }
    }, [handleRefreshToken, session.current])

    useEffect(() => {
        const timer = setInterval(checkTokenExpiry, 10000);
        return () => clearInterval(timer);
    }, [checkTokenExpiry]);

    useEffect(() => {
        session.current = data as SessionWithTokens
    }, [data])

    return (
        <RefreshTokenContext.Provider value={{}}>
            {children}
        </RefreshTokenContext.Provider>
    );
};

export default RefreshTokenProvider;