"use client"
import { useCookies } from 'react-cookie';
import { useRouter, usePathname } from 'next/navigation';
import React, { useEffect, useState } from "react";
import { isTokenExpired, checkUserToken, generateJWTusingRefTkn, generateJWT, CustomCookieSetOptions } from './utils/common';

interface WithAuthProps {
}

const withAuth = (Component: React.FC<WithAuthProps>, isAuthRequired: boolean, role: number) => {
    
  const AuthenticatedComponent: React.FC<WithAuthProps> = (props) => {
    const router = useRouter();
    const [cookies, setCookie, removeCookie] = useCookies();
    const params = usePathname();
    const [loading, setLoading] = useState(true); 

    useEffect(() => {
      const handleAuth = async () => {
        if (isAuthRequired) {
          if(!cookies.lr_ap_tk && !cookies.lr_ap_refresh_tk){
            await generateJWT(setCookie as (name: string, value: string, options?: CustomCookieSetOptions) => void);
          }
          else if(!cookies.lr_ap_tk || isTokenExpired(cookies.lr_ap_tk)){
            await generateJWTusingRefTkn(cookies, setCookie);
          }
          const isauth = checkUserToken(role, cookies, router, removeCookie, params);        
          if(isauth)  
            setLoading(false);
        }
      };
      handleAuth();
    }, [router, isAuthRequired, cookies, params]);

    if (loading) {
      return null;  
    }
    return <Component {...props} />;
  };

  AuthenticatedComponent.displayName = `WithAuth(${Component.displayName || Component.name || 'Component'})`;
  return AuthenticatedComponent;
};


export default withAuth;