import { FC, Fragment } from 'react';

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

import { MUIMenuProps } from '@material-hu/components/design-system/Menu/types';

import { ChatType, ChatListItem } from 'src/types/chats';
import { isGroupOrRegular } from 'src/utils/chats';

import {
  LeftGroupOption,
  ArchiveChatOption,
  MarkAsUnreadOption,
} from 'src/components/dashboard/chat/ChatThread';

export type ThreadItemMenuProps = MUIMenuProps & {
  thread: ChatListItem;
};

export const ThreadItemMenu: FC<ThreadItemMenuProps> = props => {
  const { thread, ...menuProps } = props;

  const { chatType, chat } = thread || {};

  const enableMarkUnread =
    isGroupOrRegular(chatType) && !chat?.markedAsUnread && !chat?.archived;

  const menuOptions = [
    {
      id: 'archive-chat',
      enabled: isGroupOrRegular(chatType),
      option: (
        <ArchiveChatOption
          thread={thread}
          onClose={menuProps?.onClose}
          archiveFromList
        />
      ),
    },
    {
      id: 'mark-unread',
      enabled: enableMarkUnread,
      option: (
        <MarkAsUnreadOption
          thread={thread}
          onClose={menuProps?.onClose}
        />
      ),
    },
    {
      id: 'left-group',
      enabled: chatType === ChatType.REGULAR_GROUP,
      option: <LeftGroupOption thread={thread} />,
    },
  ];

  const filteredOptions = menuOptions.filter(option => option.enabled);

  if (filteredOptions.length === 0) {
    return null;
  }

  return (
    <Menu
      {...menuProps}
      id="thread-item-menu"
      MenuListProps={{
        'aria-labelledby': 'thread-item-menu-button',
      }}
    >
      <Box>
        {filteredOptions.map(({ option, id }) => (
          <Fragment key={id}>{option}</Fragment>
        ))}
      </Box>
    </Menu>
  );
};

export default ThreadItemMenu;
