import { useInfiniteQuery } from 'react-query';

import { goalsKeys } from 'src/pages/dashboard/goals/queries';
import { getMostRecentCycleId } from 'src/pages/dashboard/goals/utils';
import { flatPages } from 'src/utils/pagination';

import { getGoalCycles } from '../services';
import { type GoalCycle } from '../types';

const DEFAULT_PAGINATION = { page: 0, limit: 20 };

/**
 * Subscribes to the cycles query (same key/options as CycleSelector) and returns
 * the id of the most recent cycle by endDate.
 * - Returns null if the cache is empty (first visit before data loads).
 * - Once cycles are in cache (staleTime 5min), remounts get the right default
 *   synchronously on the first render.
 *
 * Keeps MyGoals/MyTeam list queries `enabled: true` from the first render on
 * return navigations when cache is warm, so react-query applies refetchOnMount normally.
 */
export const useDefaultCycleId = (): number | null => {
  const { data: goalCyclesPages } = useInfiniteQuery(
    goalsKeys.cycles(DEFAULT_PAGINATION),
    ({ pageParam = DEFAULT_PAGINATION.page }) =>
      getGoalCycles({ ...DEFAULT_PAGINATION, page: pageParam }),
    {
      getNextPageParam: lastPage => {
        const { page, totalPages } = lastPage.data;
        return page < totalPages ? page : undefined;
      },
      keepPreviousData: true,
      staleTime: 5 * 60 * 1000,
    },
  );

  const cycles = flatPages(goalCyclesPages) as GoalCycle[];
  return getMostRecentCycleId(cycles);
};
