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

import { type LibrariesTreeItem } from '@material-hu/components/composed-components/LibrariesSidebar/types';
import { resolveSidebarModel } from '@material-hu/components/composed-components/LibrariesSidebar/utils/adapters';

import { huLibrariesRoutes } from '../routes';
import { type Article } from '../types';
import { applySidebarVisibilityFilter } from '../utils/sidebarVisibility';

import { useGetArticleChildrenTree } from './useGetArticleChildrenTree';
import { useGetRootArticles } from './useGetRootArticles';

const EMPTY_ARTICLES: Article[] = [];

export const useSidebarModel = (
  canManageArticle: boolean,
  parentId?: number,
) => {
  const isRoot = !parentId;
  const navigate = useNavigate();

  const {
    data: rootArticles = EMPTY_ARTICLES,
    isLoading: isLoadingRootArticles,
  } = useGetRootArticles();
  const { data: childrenModel, isLoading: isLoadingChildrenArticles } =
    useGetArticleChildrenTree(parentId);

  const isLoading = isLoadingRootArticles || isLoadingChildrenArticles;

  const model = useMemo(() => {
    const raw = resolveSidebarModel(isRoot, rootArticles, childrenModel);
    return applySidebarVisibilityFilter(raw, canManageArticle, isRoot);
  }, [isRoot, rootArticles, childrenModel, canManageArticle]);

  const onItemClick = useCallback(
    (item: LibrariesTreeItem) => {
      navigate(
        parentId
          ? huLibrariesRoutes.article(parentId, item.id)
          : huLibrariesRoutes.article(item.id),
      );
    },
    [navigate, parentId],
  );

  return { model, isLoading, onItemClick };
};
