import { type MouseEvent } from 'react';
import { type UseMutationResult } from 'react-query';

import { useDialogLayer } from '@material-hu/components/layers/Dialogs';

import { useLokaliseTranslation } from 'src/utils/i18n';

export function useDeleteGoalModal(
  deleteGoal: UseMutationResult<unknown, unknown, { id: number }, unknown>,
) {
  const { t } = useLokaliseTranslation('goals');
  const { openDialog, closeDialog } = useDialogLayer();

  const showDeleteModal = (id: number) => {
    openDialog({
      title: t('delete.title'),
      textBody: t('delete.description'),
      onClose: () => closeDialog(),
      primaryButtonProps: {
        children: t('general:delete'),
        onClick: (e: MouseEvent) => {
          e.stopPropagation();
          if (deleteGoal.isLoading) return;
          void deleteGoal
            .mutateAsync({ id }, { onSettled: () => closeDialog() })
            .catch(() => {
              /* Errors are surfaced via useMutation onError on the parent */
            });
        },
      },
      secondaryButtonProps: {
        children: t('general:cancel'),
        onClick: (e: MouseEvent) => {
          e.stopPropagation();
          closeDialog();
        },
      },
      dialogProps: { fullWidth: true, maxWidth: 'sm' },
    });
  };

  return { showDeleteModal };
}
