import { FC, useState } from 'react';

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

import 'src/components/dashboard/chat/ChatThreadInfo/i18n';

import MoreIcon from '@material-hu/icons/material/ExpandMore';
import Box from '@material-hu/mui/Box';
import IconButton from '@material-hu/mui/IconButton';
import Menu from '@material-hu/mui/Menu';
import MenuItem from '@material-hu/mui/MenuItem';

import useGeneralError from 'src/hooks/useGeneralError';
import {
  removeUserFromGroupChat,
  makeAdminOfGroupChat,
} from 'src/services/chats';
import { User } from 'src/types/user';
import { useTranslation } from 'src/components/dashboard/chat/ChatThreadInfo/i18n';

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

import DeleteParticipantDialog from './DeleteParticipantDialog';
import MakeAdminParticipantDialog from './MakeAdminParticipantDialog';

export type ParticipantMenuProps = {
  participant: User;
};

export const ParticipantMenu: FC<ParticipantMenuProps> = props => {
  const { participant } = props;

  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [deleteOpen, setDeleteOpen] = useState<boolean>(false);
  const [makeAdminOpen, setMakeAdminOpen] = useState<boolean>(false);

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

  const { mutate: deleteUser } = useMutation(
    (userId: number) => removeUserFromGroupChat(id, userId),
    {
      onError: err => {
        showGeneralError(err, t('ERROR_DELETE_PARTICIPANT'));
      },
      onSuccess: () => {
        queryClient.invalidateQueries(chatKeys.participants(id));
        queryClient.invalidateQueries(chatKeys.detail(id));
      },
    },
  );

  const { mutate: makeAdminUser } = useMutation(
    (userId: number) => makeAdminOfGroupChat(id, userId),
    {
      onError: err => {
        showGeneralError(err, t('ERROR_MAKE_ADMIN_PARTICIPANT'));
      },
      onSuccess: () => {
        queryClient.invalidateQueries(chatKeys.participants(id));
        queryClient.invalidateQueries(chatKeys.detail(id));
      },
    },
  );

  const openMenu = event => setAnchorEl(event.currentTarget);
  const closeMenu = () => setAnchorEl(null);

  const open = Boolean(anchorEl);

  const handleDeleteOpen = () => setDeleteOpen(true);
  const handleDeleteClose = () => setDeleteOpen(false);

  const handleDelete = (user: User) => {
    closeMenu();
    deleteUser(user.id);
  };

  const handleMakeAdminOpen = () => setMakeAdminOpen(true);
  const handleMakeAdminClose = () => setMakeAdminOpen(false);

  const handleMakeAdmin = (user: User) => {
    closeMenu();
    makeAdminUser(user.id);
  };

  return (
    <Box>
      {deleteOpen && (
        <DeleteParticipantDialog
          participant={participant}
          open={deleteOpen}
          onDelete={handleDelete}
          onClose={handleDeleteClose}
        />
      )}
      {makeAdminOpen && (
        <MakeAdminParticipantDialog
          participant={participant}
          open={makeAdminOpen}
          onMakeAdmin={handleMakeAdmin}
          onClose={handleMakeAdminClose}
        />
      )}
      <IconButton
        id="group-chat-participant-menu-button"
        aria-label={t('MORE')}
        aria-controls="toolbar-menu"
        aria-expanded={open ? 'true' : undefined}
        aria-haspopup="true"
        size="small"
        onClick={openMenu}
      >
        <MoreIcon />
      </IconButton>
      <Menu
        id="group-chat-participant-menu"
        MenuListProps={{
          'aria-labelledby': 'group-chat-participant-menu-button',
        }}
        anchorEl={anchorEl}
        open={open}
        onClose={closeMenu}
      >
        {!participant.isAdmin && (
          <MenuItem onClick={handleMakeAdminOpen}>
            {t('MAKE_ADMIN_PARTICIPANT')}
          </MenuItem>
        )}
        <MenuItem
          onClick={handleDeleteOpen}
          sx={{
            color: theme => theme.palette.error.main,
          }}
        >
          {t('DELETE')}
        </MenuItem>
      </Menu>
    </Box>
  );
};

export default ParticipantMenu;
