import { useCallback, useState } from 'react';
import { useQueries, useQuery } from 'react-query';

import { isNil } from 'lodash-es';

import { useDebounce } from 'src/hooks/useDebounce';
import { performanceKeys } from 'src/pages/dashboard/performance/queries';
import {
  getReviewStats,
  getReviewUsers,
} from 'src/pages/dashboard/performance/services';
import {
  type PendingActionFilter,
  ReviewRole,
  type UseLeaderDashboardParams,
  type UseLeaderDashboardReturn,
} from 'src/pages/dashboard/performance/types';

import {
  COLLABORATORS_PAGE_SIZE,
  PENDING_ACTION_FILTERS,
} from '../components/leader-dashboard/constants';

const useLeaderDashboard = ({
  cycleId,
  responsibleId,
}: UseLeaderDashboardParams): UseLeaderDashboardReturn => {
  const [page, setPageInternal] = useState(0);
  const [query, setQueryInternal] = useState('');
  const [selectedFilter, setSelectedFilterInternal] = useState<
    PendingActionFilter | undefined
  >(undefined);

  const { debouncedValue: debouncedQuery } = useDebounce(query, 300);

  const isResponsible = !isNil(responsibleId) && !isNil(cycleId);

  const setPage = useCallback((newPage: number) => {
    setPageInternal(newPage);
  }, []);

  const setQuery = useCallback((q: string) => {
    setQueryInternal(q);
    setPageInternal(0);
  }, []);

  const setSelectedFilter = useCallback(
    (filter: PendingActionFilter | undefined) => {
      setSelectedFilterInternal(filter);
      setPageInternal(0);
    },
    [],
  );

  const numericCycleId = cycleId ? Number(cycleId) : 0;

  const statsQuery = useQuery(
    performanceKeys.cycleStats(cycleId, responsibleId),
    () => getReviewStats(numericCycleId, responsibleId),
    {
      select: response => response.data,
      enabled: isResponsible,
    },
  );

  const filterCountQueries = useQueries(
    PENDING_ACTION_FILTERS.map(filter => ({
      queryKey: performanceKeys.users(
        cycleId,
        ReviewRole.REVIEWED,
        responsibleId,
        {
          pendingActionFilter: filter,
          page: 0,
          limit: 1,
        },
      ),
      queryFn: () =>
        getReviewUsers(cycleId, ReviewRole.REVIEWED, responsibleId, {
          pendingActionFilter: filter,
          page: 0,
          limit: 1,
        }),
      enabled: isResponsible,
      staleTime: 5 * 60 * 1000, // 5 min — chip availability rarely changes
    })),
  );

  const availableFilters = PENDING_ACTION_FILTERS.filter((_, idx) => {
    const data = filterCountQueries[idx].data as
      | { data?: { count?: number } }
      | undefined;
    return (data?.data?.count ?? 0) > 0;
  });

  const effectiveSelectedFilter =
    !isNil(selectedFilter) && availableFilters.includes(selectedFilter)
      ? selectedFilter
      : undefined;

  const teamScore = page > 0 ? statsQuery.data?.teamScore : undefined;

  const filters = {
    ...(debouncedQuery ? { q: debouncedQuery } : {}),
    ...(!isNil(effectiveSelectedFilter)
      ? { pendingActionFilter: effectiveSelectedFilter }
      : {}),
    ...(!isNil(teamScore) ? { teamScore } : {}),
  };

  const usersQuery = useQuery(
    performanceKeys.users(cycleId, ReviewRole.REVIEWED, responsibleId, {
      ...filters,
      page,
      limit: COLLABORATORS_PAGE_SIZE,
    }),
    () =>
      getReviewUsers(cycleId, ReviewRole.REVIEWED, responsibleId, {
        ...filters,
        page,
        limit: COLLABORATORS_PAGE_SIZE,
      }),
    {
      select: response => response.data,
      enabled: isResponsible,
      keepPreviousData: true,
    },
  );

  const count = usersQuery.data?.count ?? 0;
  const totalPages =
    !isNil(count) && COLLABORATORS_PAGE_SIZE > 0
      ? Math.ceil(count / COLLABORATORS_PAGE_SIZE)
      : 0;

  return {
    stats: statsQuery.data,
    statsLoading: statsQuery.isLoading,
    users: usersQuery.data?.items ?? [],
    usersLoading: usersQuery.isLoading,
    usersFetching: usersQuery.isFetching,
    totalPages,
    page,
    setPage,
    query,
    setQuery,
    debouncedQuery,
    selectedFilter: effectiveSelectedFilter,
    setSelectedFilter,
    availableFilters,
    refetch: statsQuery.refetch,
  };
};

export { useLeaderDashboard };
