import { useMutation } from 'react-query';

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

import { downloadReport } from 'src/pages/dashboard/Learning/Courses/services';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

import {
  type DownloadReportFnParams,
  type DownloadReportType,
  ReportSentTypes,
  ReportTypes,
} from '../types';

type DownloadCourseReportParams = {
  downloadType: DownloadReportType;
  downloadParams: DownloadReportFnParams;
};

export const useDownloadCourseReport = (courseId: number) => {
  const { enqueueSnackbar } = useSnackbar();
  const { t } = useLokaliseTranslation('learning');

  return useMutation(
    async (params: DownloadCourseReportParams) =>
      downloadReport({
        courseId,
        isAttendanceReport: params.downloadType === 'attendance',
        ...params.downloadParams,
      }),
    {
      onSuccess: (_, params) => {
        const isAttendanceReport = params.downloadType === 'attendance';

        const reportType: ReportTypes = isAttendanceReport
          ? ReportTypes.ATTENDANCE
          : ReportTypes.COLABS;

        logEvent(LogEvents.COURSE_REPORT_DOWNLOAD, {
          courseId,
          reportType,
          sentType: ReportSentTypes.EMAIL,
        });

        enqueueSnackbar({
          variant: 'success',
          title: t('reports.success.title'),
        });
      },
      onError: () => {
        enqueueSnackbar({
          variant: 'error',
          title: t('reports.error.sending_report'),
        });
      },
    },
  );
};
