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

import useSnackbar from '@material-hu/components/design-system/Snackbar';
import { useDrawerLayer } from '@material-hu/components/layers/Drawers';

import { useRequiredAuth } from 'src/contexts/JWTContext';
import { userMoodKeys } from 'src/hooks/useUserMood';
import { setMood } from 'src/services/userMood';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { type MoodFormValues } from './types';
import { moodFormToRequest } from './utils/transforms';

export const useSetMoodMutation = () => {
  const { user } = useRequiredAuth();
  const userId = user.id;
  const queryClient = useQueryClient();
  const { enqueueSnackbar } = useSnackbar();
  const { closeDrawer } = useDrawerLayer();
  const { t } = useLokaliseTranslation('user_mood');

  return useMutation({
    // Transform lives inside the mutationFn so any throw bubbles through
    // React Query's error flow instead of escaping the submit handler.
    mutationFn: (values: MoodFormValues) =>
      setMood(userId, moodFormToRequest(values)),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: userMoodKeys.current(userId),
      });
      enqueueSnackbar({
        title: t('user_mood:update_success'),
        variant: 'success',
      });
      closeDrawer();
    },
  });
};
