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

import { AxiosResponse, AxiosError } from 'axios';

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

import { logEvent } from 'src/config/logging';
import { deleteLibrary } from 'src/services/libraries';
import { EventName } from 'src/types/amplitude';
import { Article, LibraryErrors } from 'src/types/libraries';
import { ResponseError } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

export type SuccessResponse = AxiosResponse<unknown>;
export type ErrorResponse = AxiosError<ResponseError>;
export type Values = {};

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

  return useMutation<SuccessResponse, ErrorResponse, Values>(
    () => deleteLibrary(library.id),
    {
      onSuccess: () => {
        enqueueSnackbar({
          title: t('article.delete.success'),
          variant: 'success',
        });

        library.parentId
          ? navigate(librariesRoutes.library(library.parentId))
          : navigate(librariesRoutes.base());

        logEvent(EventName.LIBRARY_DELETE, {
          libraryId: library.id,
          parentId: library.parentId,
          title: library.title,
        });

        queryClient.invalidateQueries(librariesKeys.all(), {
          predicate: query => {
            const queryKey = query.queryKey as Array<any>;
            return !queryKey?.includes(library.id);
          },
        });
      },
      onError: err => {
        if (err.response.data?.code === LibraryErrors.DELETE_WITH_CHILDREN) {
          enqueueSnackbar({
            title: t('library.delete.error.children'),
            variant: 'error',
          });
        } else {
          enqueueSnackbar({
            title: t('article.delete.error'),
            variant: 'error',
          });
        }
      },
    },
  );
};

export default useDeleteLibrary;
