import { useCallback } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

import { huLibrariesRoutes } from '../routes';
import { type LibraryNavigationState } from '../types';

import { useArticleId } from './useArticleId';
import { useCachedArticle } from './useCachedArticle';

export const useArticleNavigation = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { rootId, articleId } = useArticleId();
  const { article } = useCachedArticle(articleId);

  const navigateBack = useCallback(() => {
    const state = location.state as LibraryNavigationState | null;
    if (state?.search) return navigate(-1);

    if (!article?.parentId || !rootId) {
      return navigate(huLibrariesRoutes.base());
    }
    navigate(huLibrariesRoutes.article(rootId, article.parentId));
  }, [location.state, article?.parentId, rootId, navigate]);

  return { navigateBack };
};
