import { Navigate, Outlet } from 'react-router-dom';

import { useArticleId } from '../hooks/useArticleId';
import { useGetArticleTree } from '../hooks/useGetArticleTree';
import { useGetRootArticles } from '../hooks/useGetRootArticles';
import { useLibraryAccessGuard } from '../hooks/useLibraryAccessGuard';
import { huLibrariesRoutes } from '../routes';

/**
 * @description Layout for `/library/:rootId`.
 * Validates that `rootId` is numeric and exists in root articles; redirects to home otherwise.
 * When `rootId` is not a root article, fetches the article tree to check if it's a child —
 * if so, silently redirects to the correct URL instead of showing an error.
 */
const RootArticleLayout = () => {
  const { rootId } = useArticleId();
  const {
    data: rootArticles,
    isLoading: isRootLoading,
    isFetching: isRootFetching,
    isFetched: isRootFetched,
  } = useGetRootArticles();

  const isRootFetchSettled = isRootFetched && !isRootLoading && !isRootFetching;
  const isUnknownRoot =
    isRootFetchSettled && !rootArticles?.some(article => article.id === rootId);

  const {
    data: articleTree,
    isLoading: isTreeLoading,
    isFetching: isTreeFetching,
    isFetched: isTreeFetched,
  } = useGetArticleTree(rootId, { enabled: isUnknownRoot });

  const isTreeFetchSettled = isTreeFetched && !isTreeLoading && !isTreeFetching;
  const isChildArticle =
    isUnknownRoot &&
    isTreeFetchSettled &&
    !!articleTree &&
    articleTree.id !== rootId;
  const isInvalidAccess =
    isUnknownRoot && isTreeFetchSettled && !isChildArticle;

  useLibraryAccessGuard({
    resetKey: `${rootId}`,
    isInvalid: !rootId || isInvalidAccess,
  });

  if (isUnknownRoot && !isTreeFetchSettled) return null;

  if (isChildArticle && rootId && articleTree) {
    return (
      <Navigate
        to={huLibrariesRoutes.article(articleTree.id, rootId)}
        replace
      />
    );
  }

  return <Outlet />;
};

export default RootArticleLayout;
