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

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

import { logEvent } from 'src/config/logging';
import { updateLibrary } from 'src/services/libraries';
import { EventName } from 'src/types/amplitude';
import { LibraryValues, Article } from 'src/types/libraries';
import { RequestError, RequestSuccess } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { librariesKeys } from '../queries';
import { librariesRoutes } from '../routes';
import { formatLibraryData } from '../utils';

const HTTP_NOT_FOUND = 404;

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

export const useUpdateLibrary = (library: Article, options: TOptions = {}) => {
  const { t } = useLokaliseTranslation('libraries');
  const { enqueueSnackbar } = useHuSnackbar();
  const queryClient = useQueryClient();
  const navigate = useNavigate();

  return useMutation<TSuccess, TError, TValues>(
    async values =>
      updateLibrary(library.id, await formatLibraryData(values, library)),
    {
      ...options,
      onSuccess: (...args) => {
        options.onSuccess?.(...args);
        enqueueSnackbar({
          title: t('article.save.success'),
          variant: 'success',
        });
        logEvent(EventName.LIBRARY_CONTENT_EDIT_SAVE, {
          libraryId: library.id,
          parentId: library.parentId,
          title: library.title,
        });
        queryClient.invalidateQueries(librariesKeys.all());
      },
      onError: (err, ...args) => {
        options.onError?.(err, ...args);

        const isNotFound = err?.response?.status === HTTP_NOT_FOUND;

        if (isNotFound) {
          enqueueSnackbar({
            title: t('library.not_available'),
            variant: 'error',
          });
          navigate(librariesRoutes.base(), { replace: true });
          return;
        }

        enqueueSnackbar({
          title: t('article.save.error'),
          variant: 'error',
        });
      },
    },
  );
};

export default useUpdateLibrary;
