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

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

import { updateLibrary } from 'src/services/libraryService';
import { LibraryValues, KnowledgeLibraryArticle } from 'src/types/library';
import { RequestError, RequestSuccess } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { logEvent, LogEvents } from 'src/utils/logging';

import { librariesKeys } from '../queries';
import { formatLibrary } from '../utils';

export type TSuccess = RequestSuccess<typeof updateLibrary>;
export type TError = RequestError;
export type TValues = LibraryValues;

export const useUpdateLibrary = (
  library?: KnowledgeLibraryArticle,
  options?: UseMutationOptions<TSuccess, TError, TValues>,
) => {
  const { t } = useLokaliseTranslation('libraries');
  const { enqueueSnackbar } = useHuSnackbar();
  const queryClient = useQueryClient();

  return useMutation<TSuccess, TError, TValues>(
    values => {
      if (!library?.id) throw new Error('Library id required');
      return updateLibrary(library.id, formatLibrary(values));
    },
    {
      ...options,
      onSuccess: (response, values, context) => {
        options?.onSuccess?.(response, values, context);

        logEvent(LogEvents.WIDGET_LIBRARY_UPDATE, {
          widgetId: response.data.id,
          parentId: response.data.parentId,
          name: response.data.title,
        });

        enqueueSnackbar({
          title: t('article.save.success'),
          variant: 'success',
        });
        queryClient.invalidateQueries(librariesKeys.all());
      },
      onError: (error, values, context) => {
        options?.onError?.(error, values, context);
      },
    },
  );
};

export default useUpdateLibrary;
