import { useMemo } from 'react';
import { useInfiniteQuery } from 'react-query';

import { useDebounce } from '@material-hu/hooks/useDebounce';

import usePaginatedQueryState from 'src/hooks/usePaginatedQueryState';
import { getSessionAttendance } from 'src/pages/dashboard/Learning/Sessions/services';
import { sToMs } from 'src/utils/timeUtils';

import { TABLE_PAGE_SIZE } from '../constants';
import { sessionsKeys } from '../queries';
import { type SessionsPaginationParams } from '../types';

import { useManageAttendanceParams } from './useManageAttendanceParams';

export const useGetSessionAttendance = (sessionId?: number) => {
  const { search } = useManageAttendanceParams();
  const debouncedSearch = useDebounce(search);

  const params: SessionsPaginationParams = {
    page: 1,
    limit: TABLE_PAGE_SIZE,
    q: debouncedSearch || undefined,
  };

  const { data, hasNextPage, isFetchingNextPage, fetchNextPage, ...query } =
    useInfiniteQuery({
      queryKey: sessionsKeys.attendance.table(sessionId!, params),
      queryFn: ({ pageParam = 1 }) => {
        if (!sessionId) throw new Error('Session ID is required');
        return getSessionAttendance(sessionId, { ...params, page: pageParam });
      },
      getNextPageParam: lastPage => {
        const lastPageData = lastPage.data;
        return lastPageData.page === lastPageData.totalPages
          ? undefined
          : lastPageData.page + 1;
      },
      keepPreviousData: true,
      staleTime: sToMs(60),
      enabled: !!sessionId,
    });

  const collaborators = useMemo(
    () => data?.pages.flatMap(page => page.data.items) || [],
    [data?.pages],
  );
  const firstSessionsPage = data?.pages[0].data;

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

  const queryState = usePaginatedQueryState(
    firstSessionsPage,
    query.status,
    debouncedSearch !== '',
  );

  return {
    collaborators,
    handleFetchNextPage,
    isFetchingNextPage,
    totalCount: data?.pages[0].data.count ?? 0,
    queryState,
    ...query,
  };
};
