import { useInfiniteQuery } from 'react-query';

import { type PaginationParams } from '@material-hu/hooks/useHuPagination';

import { MIN_SEARCH_LENGTH } from '../constants';
import { librariesKeys } from '../queries';
import { getArticlesSearch } from '../services';
import { ArticleStatus } from '../types';

export const useGetArticlesSearch = (search: string) => {
  const pagination: Partial<PaginationParams> = {
    page: 1,
    limit: 20,
    search,
  };

  const { data, hasNextPage, isFetchingNextPage, fetchNextPage, ...query } =
    useInfiniteQuery({
      queryKey: librariesKeys.article.search(pagination),
      queryFn: ({ pageParam = 1 }) =>
        getArticlesSearch({ ...pagination, page: pageParam }),
      getNextPageParam: lastPage => {
        const { page, totalPages } = lastPage.data;
        return page < totalPages ? page + 1 : undefined;
      },
      enabled: !!search && search.length >= MIN_SEARCH_LENGTH,
      keepPreviousData: true,
    });

  const articles = data?.pages.flatMap(page => page.data.items) || [];
  const firstPage = data?.pages[0]?.data;

  const visibleArticles = articles.filter(
    a => a.status === ArticleStatus.ENABLED,
  );

  const handleFetchNextPage = () => {
    hasNextPage && !isFetchingNextPage && fetchNextPage();
  };

  // While paginating, fall back to the server's total (which counts disabled
  // items too) since we can't know how many disabled items live on unloaded
  // pages. Once everything is loaded, use the accurate visible-only count.
  const totalCount = hasNextPage
    ? (firstPage?.count ?? 0)
    : visibleArticles.length;

  return {
    visibleArticles,
    handleFetchNextPage,
    isFetchingNextPage,
    hasNextPage,
    totalCount,
    ...query,
  };
};
