import { FC, useState } from 'react';

import ExpandIcon from '@material-hu/icons/material/ExpandMore';
import Box from '@material-hu/mui/Box';
import IconButton from '@material-hu/mui/IconButton';

import { isGroupOrRegular } from 'src/utils/chats';

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

import { ThreadItemMenuProps, ThreadItemMenu } from './ThreadItemMenu';

export type ThreadItemIconMenuProps = Omit<
  ThreadItemMenuProps,
  'open' | 'anchorEl'
>;

export const ThreadItemIconMenu: FC<ThreadItemIconMenuProps> = props => {
  const { thread, onClose = () => null, ...menuProps } = props;

  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);

  const open = Boolean(anchorEl);
  const { t } = useTranslation();

  const openMenu = event => {
    event.stopPropagation();
    setAnchorEl(event.currentTarget);
  };

  const closeMenu = (event, reason) => {
    event.stopPropagation();
    onClose(event, reason);
    setAnchorEl(null);
  };

  if (!isGroupOrRegular(thread?.chatType)) {
    return null;
  }

  return (
    <Box>
      <IconButton
        id="thread-item-menu-button"
        aria-label={t('CHAT_MENU')}
        aria-controls="thread-item-menu"
        aria-expanded={open ? 'true' : undefined}
        aria-haspopup="true"
        onClick={openMenu}
        sx={{ p: 0 }}
      >
        <ExpandIcon />
      </IconButton>
      <ThreadItemMenu
        {...menuProps}
        thread={thread}
        anchorEl={anchorEl}
        open={open}
        onClose={closeMenu}
      />
    </Box>
  );
};

export default ThreadItemIconMenu;
