import { useMutation, useQuery } from 'react-query';

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

import { createInvitation } from 'src/services/events';
import { getGroups } from 'src/services/groups';
import { EventInvitation } from 'src/types/events';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

const LIMIT = 100;

type Props = {
  canViewGroups?: boolean;
  groupCheckBoxSelected?: boolean;
  eventId?: number;
};

export const useEventGroups = ({
  canViewGroups,
  groupCheckBoxSelected,
  eventId,
}: Props) => {
  const { enqueueSnackbar } = useHuSnackbar();
  const { t } = useLokaliseTranslation('events');

  const { data: groups, isLoading: isGroupsLoading } = useQuery(
    groupsKeys.allList(),
    () => getGroups({ page: 1, limit: LIMIT }),
    {
      select: r =>
        r.data.items.map(item => ({
          label: item.title,
          value: item.id,
        })),
      enabled: !!canViewGroups && !!groupCheckBoxSelected && !eventId,
    },
  );

  const { mutate: invitationMutation } = useMutation(
    (data: EventInvitation) => createInvitation(data.id, data),
    {
      onSuccess: r => {
        enqueueSnackbar({
          title:
            r.data.count === 1
              ? t('INVITATION_SENT_one', { count: r.data.count })
              : t('INVITATION_SENT_other', { count: r.data.count }),
          variant: 'info',
        });
      },
    },
  );

  return {
    groups,
    isGroupsLoading,
    invitationMutation,
  };
};
