import { useQuery } from 'react-query';

import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import useGeneralError from 'src/hooks/useGeneralError';
import {
  getGroupStatsSummary,
  getGroupMostActiveMembers,
  getGroupMostActiveMembersReport,
} from 'src/services/groups';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

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

export const useGroupStatsSummary = (groupId: string) => {
  const showGeneralError = useGeneralError();
  const { t } = useTranslation();

  return useQuery(
    groupsKeys.featuredMembers.summary(groupId),
    () => getGroupStatsSummary(groupId),
    {
      onError: error => {
        showGeneralError(error, t('group:error_getting_group_stats'));
      },
      enabled: !!groupId,
    },
  );
};

export const useGroupMostActiveMembers = (groupId: string) => {
  const showGeneralError = useGeneralError();
  const { t } = useTranslation();

  return useQuery(
    groupsKeys.featuredMembers.activeMembers(groupId),
    () => getGroupMostActiveMembers(groupId),
    {
      onError: error => {
        showGeneralError(error, t('group:error_getting_active_members'));
      },
      enabled: !!groupId,
    },
  );
};

export const useGroupMostActiveMembersReport = (
  groupId: string,
  email: string,
  enabled = false,
) => {
  const showGeneralError = useGeneralError();
  const { enqueueSnackbar } = useHuSnackbar();
  const { t } = useTranslation();

  return useQuery(
    groupsKeys.featuredMembers.activeMembersReport(groupId, email),
    () => getGroupMostActiveMembersReport(groupId, email),
    {
      onError: error => {
        showGeneralError(error, t('group:error_generating_report'));
      },
      onSuccess: () => {
        enqueueSnackbar({
          title: t('group:report_email_sent'),
          variant: 'success',
        });
      },
      enabled: enabled && !!groupId && !!email,
      staleTime: 0, // Always refetch when enabled
      cacheTime: 0, // Don't cache the response
    },
  );
};
