import { useMutation } from 'react-query';

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

import { queryClient } from 'src/config/react-query';
import { updateSessionAttendance } from 'src/pages/dashboard/Learning/Sessions/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { sessionsKeys } from '../queries';
import { type UpdateSessionAttendanceParams } from '../types';

export const useUpdateSessionAttendance = (sessionId?: number) => {
  const { enqueueSnackbar } = useSnackbar();
  const { t } = useLokaliseTranslation('learning');

  return useMutation({
    mutationFn: (params: UpdateSessionAttendanceParams) => {
      if (!sessionId) throw new Error('Session ID is required');
      return updateSessionAttendance(sessionId, params);
    },
    onSuccess: (_, params) => {
      queryClient.invalidateQueries(sessionsKeys.attendance.all());

      // Only show success message if its bulk update
      if (params.userIds.length > 1) {
        enqueueSnackbar({
          title: t('session.attendance.asist_marked_successfully'),
          variant: 'success',
        });
      }
    },
    onError: () => {
      enqueueSnackbar({
        title: t('session.attendance.asist_marked_error'),
        variant: 'error',
      });
    },
  });
};
