import { FC } from 'react';

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

import Typography from '@material-hu/mui/Typography';

import useGeneralError from 'src/hooks/useGeneralError';
import { deleteMessage } from 'src/services/chats';

import AcceptCancelDialog from 'src/components/AcceptCancelDialog';
import { useTranslation } from 'src/components/dashboard/chat/i18n';
import { chatKeys } from 'src/components/dashboard/chat/queries';

export type ChatDeleteMessageProps = {
  open: boolean;
  onCancel: (event) => void;
  messageId: string | number;
  chatId: number;
};

const deleteMessageWrap = ({ chatId, messageId }) =>
  deleteMessage(chatId, messageId);

export const ChatDeleteMessage: FC<ChatDeleteMessageProps> = props => {
  const { open, onCancel, messageId, chatId } = props;

  const { t } = useTranslation();
  const showGeneralError = useGeneralError();
  const queryClient = useQueryClient();

  const postMutation = useMutation(deleteMessageWrap);

  const handleAccept = async event => {
    try {
      await postMutation.mutateAsync({ chatId, messageId });
      queryClient.invalidateQueries(chatKeys.messages.list(chatId));
      queryClient.invalidateQueries(chatKeys.list());
      onCancel(event);
    } catch (error) {
      showGeneralError(error, t('DELETE_MESSAGE_ERROR'));
      onCancel(event);
    }
  };

  return (
    <AcceptCancelDialog
      open={open}
      title={t('DELETE_MESSAGE')}
      acceptLabel={t('ACCEPT')}
      showCancel
      isLoading={postMutation.isLoading}
      onAccept={handleAccept}
      onCancel={onCancel}
      onClose={onCancel}
      maxWidth="sm"
    >
      <Typography>{t('DELETE_MESSAGE_CONFIRMATION')}</Typography>
    </AcceptCancelDialog>
  );
};

export default ChatDeleteMessage;
