'use client';

import { useState, useEffect, useCallback } from 'react';
import { paths } from '@/routes/paths';
import { useRouter } from '@/hooks';
import { SplashScreen } from '@/shared/components/loading-screen';
import { useAuthContext } from '@/hooks';
import { getTokenInfo } from '@/utils/token';
import { TokenPayload } from '@/shared/types/user';

// ----------------------------------------------------------------------

const loginPaths: Record<string, string> = {
  jwt: paths.auth.jwt.login,
};

// ----------------------------------------------------------------------

type Props = {
  children: React.ReactNode;
};

export default function AuthGuard({ children }: Props) {
  const { loading } = useAuthContext();

  return <>{loading ? <SplashScreen /> : <Container>{children}</Container>}</>;
}

// ----------------------------------------------------------------------

function Container({ children }: Props) {
  const router = useRouter();
  const [checked, setChecked] = useState(false);

  const check = useCallback(() => {
    const token = localStorage.getItem("token");

    if (token) {
      const userInfo: TokenPayload = getTokenInfo(token);
      // Check token validity
      if (userInfo && userInfo.isValid) {
        setChecked(true);
      } else {
        // Token invalid, remove it and redirect to login
        handleLogout();
      }
    } else {
      handleLogout();
    }
  }, [router]);

  // Helper function for logout
  const handleLogout = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("refreshToken");
    localStorage.removeItem("expirationDurationInSec");
    router.push("/auth/jwt/login");
  };

  useEffect(() => {
    check();
  }, [check]);

  if (!checked) {
    return <SplashScreen />; // Or return a loading spinner
  }

  return <>{children}</>;
}