import { useLocation, useNavigate } from 'react-router-dom';
import { getExpirationDateFromToken, useAuth } from '../hooks/useAuth';
import { useEffect } from 'react';

const AuthWrapper = ({ children }) => {
  const location = useLocation();
  const navigate = useNavigate();
  const { logout } = useAuth();

  useEffect(() => {
    const user = localStorage.getItem('user');
    const isLoginPage = location.pathname === '/login';

    if (!user && !isLoginPage) {
      navigate('/', { replace: true });
    }

    checkUserToken();
  }, [location.pathname, navigate]);

  const checkUserToken = () => {
    const user = localStorage.getItem('user');
    if (!user) return navigate('/');

    const parsedUser = JSON.parse(user);
    if (parsedUser) {
      let expiredDate = getExpirationDateFromToken(parsedUser.token);
      const currentDate = new Date();

      if (expiredDate < currentDate) {
        logout();
        navigate('/');
      }
    }
  };

  return <>{children}</>;
};

export default AuthWrapper;
