import { useNavigate } from 'react-router-dom';

import { type BreadcrumbLink } from '@material-hu/components/design-system/Breadcrumbs/types';

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

import useLibrariesTitle from './useLibrariesTitle';

export const useArticleBreadcrumb = (tree?: ArticleTree): BreadcrumbLink[] => {
  const navigate = useNavigate();
  const librariesTitle = useLibrariesTitle();

  if (!tree) return [];

  const rootId = tree.id;

  const handleClick = (ancestorId?: number | null) => () => {
    if (!ancestorId) {
      navigate(huLibrariesRoutes.base());
      return;
    }
    navigate(huLibrariesRoutes.article(rootId, ancestorId));
  };

  const path: BreadcrumbLink[] = [
    { title: librariesTitle, onClick: handleClick() },
  ];

  path.push({ title: tree.title, onClick: handleClick(tree.id) });

  let current = tree;
  while (current.children?.length) {
    [current] = current.children;
    path.push({ title: current.title, onClick: handleClick(current.id) });
  }

  return path;
};
