import { createContext, useEffect, useRef, useCallback } from 'react';
import { apiPath } from 'auth/utils';
import { REFRESH_TOKEN } from 'utils/ApiPathConst';
import axios from 'axios';
import { 
  isUserLoggedIn,
} from "utils/Utils";
const RefreshTokenContext = createContext();

const RefreshTokenProvider = ({ children }) => {
  const token = useRef(localStorage.getItem('accessToken'));
  const isRefresh = useRef(false);

  // handle Refresh Token Logic
  const handleRefreshToken = useCallback(() => {
    if (!isRefresh.current) {
      const refreshToken = localStorage.getItem('refreshToken');
      isRefresh.current = true;
      axios
        .post(`${apiPath}${REFRESH_TOKEN}`, {
          refreshToken: refreshToken
        })
        .then((response) => {
          if (response.status === 200) {
            const newAccessToken = response.data.accessToken;
            const newRefreshToken = response.data.refreshToken;
            localStorage.setItem('accessToken', newAccessToken);
            localStorage.setItem('refreshToken', newRefreshToken);
            token.current = newAccessToken;
            isRefresh.current = false;
          } else {
            token.current = null;
            isRefresh.current = false;
          }
        })
        .catch((refreshError) => {
          console.log('Failed to refresh token');
          if (refreshError != undefined){
            console.log(refreshError)
          }
          token.current = null
          isRefresh.current = false;
        });
    }
  }, []);

  // Function to check token expiry
  const checkTokenExpiry = useCallback(() => {
    // Check if token is present and its expiry time
    if (token.current) {
      const tokenExp = JSON.parse(atob(token.current.split('.')[1])).exp;
      const currentTime = Math.floor(Date.now() / 1000);
      const expiryTime = tokenExp - 30; // Refresh 30 seconds before expiry
    //   console.log("check refresh Token");      
    //   console.log(currentTime);      
    //   console.log(new Date(currentTime*1000).toLocaleString());      
    //   console.log(expiryTime);
    //   console.log(new Date(expiryTime*1000).toLocaleString());      
    //   console.log('accessToken: ' + localStorage.getItem('accessToken'));
    //   console.log('refreshToken: ' + localStorage.getItem('refreshToken'));
      if (currentTime >= expiryTime) {
        if(isUserLoggedIn()){
          handleRefreshToken();
        }
      }
    }
  }, [token]);

  // Start the timer on component mount
  useEffect(() => {
    const timer = setInterval(checkTokenExpiry, 10000); // Check every 10 second
    return () => clearInterval(timer); // Cleanup timer on unmount
  }, [checkTokenExpiry]);

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

export { RefreshTokenContext, RefreshTokenProvider };
