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

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

import { logEvent } from 'src/config/logging';
import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import { exitGroupChat } from 'src/services/chats';
import { EventName } from 'src/types/amplitude';

import AcceptCancelDialog from 'src/components/AcceptCancelDialog';
import { useTranslation } from 'src/components/dashboard/chat/i18n';
import { refetchListChats } from 'src/components/dashboard/chat/queries';
import { chatRoutes } from 'src/components/dashboard/chat/routes';

export type LeftGroupButtonProps = {
  onClick: (event) => void;
};

export type LeftGroupProps = {
  button: FC<LeftGroupButtonProps>;
  threadId: number;
};

const LeftGroup: FC<LeftGroupProps> = props => {
  const { threadId, button } = props;

  const [confirmOpen, setConfirmOpen] = useState<boolean>(false);

  const { t } = useTranslation();
  const showGeneralError = useGeneralError();
  const navigate = useNavigate();
  const { user } = useAuth();

  const { isLoading, mutate: handleLeft } = useMutation(
    () => exitGroupChat(threadId, user.id),
    {
      onError: err => {
        showGeneralError(err, t('ERROR_LEFT_GROUP'));
      },
      onSuccess: () => {
        logEvent(EventName.CHAT_GROUP_LEAVE, { chatId: threadId });
        navigate(chatRoutes.chats());
        refetchListChats();
      },
    },
  );

  const openConfirm = event => {
    event.stopPropagation();
    setConfirmOpen(true);
  };

  const closeConfirm = event => {
    event.stopPropagation();
    setConfirmOpen(false);
  };

  const handleAccept = event => {
    event.stopPropagation();
    handleLeft();
  };

  return (
    <Box
      sx={{
        display: 'flex',
        flex: 1,
      }}
    >
      <AcceptCancelDialog
        open={confirmOpen}
        onCancel={closeConfirm}
        onBackdropClick={closeConfirm}
        onAccept={handleAccept}
        isLoading={isLoading}
        acceptLabel={t('LEFT_GROUP')}
        showCancel
      >
        <Typography>{t('CONFIRM_LEFT_GROUP')}</Typography>
      </AcceptCancelDialog>
      {button({
        onClick: openConfirm,
      })}
    </Box>
  );
};

export default LeftGroup;
