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

import {
  getStateName,
  parseCoordinatorPanelFilters,
} from 'src/pages/dashboard/serviceManagement/utils';
import {
  getAssociatedMembers,
  getServiceMetrics,
} from 'src/pages/dashboard/serviceManagement/services';
import { CoordinatorTaskFilters } from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { serviceManagementKeys } from '../queries';

type Props = {
  helpDeskId: string;
  filters: CoordinatorTaskFilters;
};

const ASSOCIATED_MEMBERS_LIMIT = 12;

const useCoordinatorDashboard = ({ helpDeskId, filters }: Props) => {
  const { t } = useLokaliseTranslation('service_management');

  const params = useMemo(() => {
    const parsedFilters = parseCoordinatorPanelFilters(filters);
    return {
      helpDeskId,
      ...parsedFilters,
    };
  }, [helpDeskId, filters]);

  const {
    data: serviceMetrics,
    isLoading: isLoadingServiceMetrics,
    refetch: refetchServiceMetrics,
    isError: isErrorServiceMetrics,
    isRefetching: isRefetchingServiceMetrics,
  } = useQuery(
    serviceManagementKeys.helpDesk.serviceMetrics(helpDeskId, params),
    () => getServiceMetrics(params),
    {
      select: data => data.data,
      refetchOnMount: false,
      refetchOnWindowFocus: false,
      onError: () => {
        // Do nothing: prevent global error toast
      },
    },
  );

  const associatedMembersInfiniteQuery = useInfiniteQuery(
    serviceManagementKeys.helpDesk.associatedMembers(helpDeskId, params),
    ({ pageParam = 1 }) =>
      getAssociatedMembers({
        ...params,
        page: pageParam,
        limit: ASSOCIATED_MEMBERS_LIMIT,
      }),
    {
      getNextPageParam: lastPage =>
        lastPage.data.page === lastPage.data.totalPages
          ? undefined
          : lastPage.data.page + 1,
      refetchOnWindowFocus: false,
      refetchOnMount: false,
    },
  );

  const serviceMetricsChartData: [string[], number[]] | [null, null] =
    useMemo(() => {
      if (!serviceMetrics) {
        return [null, null];
      }
      const labels = Object.keys(serviceMetrics.tasksByStatus).map(status =>
        t(getStateName(status)),
      );

      const values = Object.values(serviceMetrics.tasksByStatus);
      return [labels, values];
    }, [t, serviceMetrics]);

  return {
    serviceMetrics,
    isLoadingServiceMetrics,
    refetchServiceMetrics,
    isErrorServiceMetrics,
    serviceMetricsChartData,
    isRefetchingServiceMetrics,
    associatedMembersInfiniteQuery,
  };
};

export default useCoordinatorDashboard;
