import { type InfiniteData, useMutation } from 'react-query';

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

import { queryClient } from 'src/config/react-query';
import { deletePath } from 'src/pages/dashboard/Learning/Paths/services';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

import { pathsKeys } from '../queries';

import { type TSuccess } from './useGetPaths';

export const useDeletePath = () => {
  const { enqueueSnackbar } = useHuSnackbar();
  const { t } = useLokaliseTranslation('learning');

  return useMutation({
    mutationFn: (pathId: number) => deletePath(pathId),
    onSuccess: (_, pathId: number) => {
      logEvent(LogEvents.PATH_DELETED, { pathId });

      // Get the paths list
      const pathsQueries = queryClient.getQueriesData<InfiniteData<TSuccess>>(
        pathsKeys.paths.all(),
      );

      // Optimistically delete the path from the list
      pathsQueries.forEach(([queryKey, data]) => {
        if (!data) return;

        const newPages = data.pages.map(page => ({
          ...page,
          data: {
            ...page.data,
            learningPaths: {
              ...page.data.learningPaths,
              items: page.data.learningPaths.items.filter(
                path => path.id !== pathId,
              ),
            },
          },
        }));

        queryClient.setQueryData(queryKey, { ...data, pages: newPages });
      });

      enqueueSnackbar({
        title: t('path.delete.success'),
        variant: 'success',
      });
      queryClient.invalidateQueries(pathsKeys.paths.all());
      queryClient.invalidateQueries(pathsKeys.stats());
    },
    onError: () => {
      enqueueSnackbar({
        title: t('path.delete.error'),
        description: t('general:retry_later'),
        variant: 'error',
      });
    },
  });
};
