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

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

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

import { useAuth } from 'src/contexts/JWTContext';
import { archiveChat } from 'src/services/chats';
import { ChatListItem } from 'src/types/chats';

import { useTranslation } from 'src/components/dashboard/chat/i18n';
import {
  refetchListChats,
  refetchArchiveListChats,
} from 'src/components/dashboard/chat/queries';
import {
  addChatNotification,
  removeChatNotification,
} from 'src/components/dashboard/chat/queries';

export type ArchiveChatOptionProps = {
  thread: ChatListItem;
  archiveFromList?: boolean;
  onClose?: any;
};

export type ArchiveUpdate = {
  chatId: number;
  userId: number;
  archiveState: boolean;
};

const ArchiveChatOption: FC<ArchiveChatOptionProps> = props => {
  const { thread, archiveFromList, onClose } = props;
  const { user } = useAuth();
  const { enqueueSnackbar } = useSnackbar();
  const navigate = useNavigate();

  const { unreadMessages, markedAsUnread } = thread?.chat || {};

  const mutation = useMutation((data: ArchiveUpdate) => archiveChat(data), {
    onSuccess: (_, { archiveState }) => {
      if ((unreadMessages && archiveFromList) || markedAsUnread)
        archiveState ? removeChatNotification() : addChatNotification();
      navigate('/chats');
      refetchListChats();
      refetchArchiveListChats();
      enqueueSnackbar({
        title: t(archiveState ? 'ARCHIVE_SUCCESS' : 'UNARCHIVE_SUCCESS'),
        variant: 'success',
      });
    },
  });

  const { t } = useTranslation();

  const handleClick = event => {
    event.stopPropagation();
    const data = {
      chatId: thread.chat.id,
      userId: user.id,
      archiveState: !thread.chat.archived,
    };
    mutation.mutate(data);
    onClose(event);
  };

  return (
    <MenuItem onClick={handleClick}>
      <Typography
        sx={{
          display: 'flex',
          alignItems: 'center',
        }}
      >
        {thread.chat.archived ? t('UNARCHIVE_CHAT') : t('ARCHIVE_CHAT')}
      </Typography>
    </MenuItem>
  );
};

export default ArchiveChatOption;
