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

import TagIcon from '@material-hu/icons/material/Tag';
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 ConfirmChangeChannelDialog from 'src/pages/dashboard/tickets/components/ConfirmChangeChannelDialog';
import NoChangeChannelDialog from 'src/pages/dashboard/tickets/components/NoChangeChannelDialog';
import { useTranslation } from 'src/pages/dashboard/tickets/i18n';
import { ticketRoutes } from 'src/pages/dashboard/tickets/routes';
import { changeTopic } from 'src/services/tickets';
import { ChatListItem } from 'src/types/chats';
import { Topic } from 'src/types/tickets';
import { isTopicResponsible } from 'src/utils/chats';

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

import ChangeChannelDialog from './ChangeChannelDialog';

const changeTopicWrap = ({ id, topicId }) => changeTopic(id, topicId);

export type ChangeChannelOptionProps = {
  thread: ChatListItem;
};

const ChangeChannelOption: FC<ChangeChannelOptionProps> = props => {
  const { thread } = props;

  const [openChangeChannel, setOpenChangeChannel] = useState<boolean>(false);
  const [openNoChangeChannel, setOpenNoChangeChannel] =
    useState<boolean>(false);
  const [openConfirmationChangeChanel, setOpenConfirmationChangeChanel] =
    useState<boolean>(false);
  const [topic, setTopic] = useState<Topic>(null);

  const { user } = useAuth();
  const { t } = useTranslation();
  const { enqueueSnackbar } = useSnackbar();
  const queryClient = useQueryClient();
  const navigate = useNavigate();

  const changeTopicMutation = useMutation(changeTopicWrap, {
    onSuccess: () => {
      const id = thread?.chat.id;

      queryClient.invalidateQueries(ticketKeys.list.all());

      if (isTopicResponsible(topic, user.id)) {
        queryClient.invalidateQueries(ticketKeys.detail(id));
        queryClient.invalidateQueries(ticketKeys.messages.list(id));
      } else {
        navigate(ticketRoutes.tickets());
      }

      enqueueSnackbar({
        title: t('SUCCESS_CHANGING_TOPIC_TICKET'),
        variant: 'success',
      });
    },
    onError: () => {
      setOpenNoChangeChannel(true);
    },
    onSettled: () => {
      handleCloseConfirmationChangeChanel();
    },
  });

  const handleOpenChangeChanel = () => setOpenChangeChannel(true);
  const handleCloseChangeChanel = () => setOpenChangeChannel(false);
  const handleOpenConfirmationChangeChanel = () =>
    setOpenConfirmationChangeChanel(true);
  const handleCloseConfirmationChangeChanel = () =>
    setOpenConfirmationChangeChanel(false);

  const handleChangeTopic = () => {
    const ticketId = thread?.id;

    changeTopicMutation.mutate({
      id: Number(ticketId),
      topicId: topic.id,
    });
  };

  const handleCloseNoChangeDialog = () => setOpenNoChangeChannel(false);

  const handleSelect = (topicSelected: Topic) => {
    handleCloseChangeChanel();
    handleOpenConfirmationChangeChanel();
    setTopic(topicSelected);
  };

  return (
    <>
      <ChangeChannelDialog
        open={openChangeChannel}
        onClose={handleCloseChangeChanel}
        onChangeChannel={handleSelect}
        topicId={thread.topic.id}
      />
      <ConfirmChangeChannelDialog
        name={topic?.name}
        open={openConfirmationChangeChanel}
        onCancel={handleCloseConfirmationChangeChanel}
        onBackdropClick={handleCloseConfirmationChangeChanel}
        onAccept={handleChangeTopic}
        isLoading={changeTopicMutation.isLoading}
      />
      <NoChangeChannelDialog
        title={t('ERROR_CHANGING_TOPIC_TICKET_TITLE')}
        description={t('ERROR_CHANGING_TOPIC_TICKET_DESCRIPTION', {
          nameTopic: topic?.name,
        })}
        open={openNoChangeChannel}
        onAccept={handleCloseNoChangeDialog}
      />
      <MenuItem onClick={handleOpenChangeChanel}>
        <Typography
          sx={{
            display: 'flex',
            alignItems: 'center',
          }}
        >
          <TagIcon sx={{ mr: 1 }} />
          {t('CHANGE_CHANNEL')}
        </Typography>
      </MenuItem>
    </>
  );
};

export default ChangeChannelOption;
