import { MouseEvent } from 'react';

import { EmojiClickData } from 'emoji-picker-react';

import Menu from '@material-hu/mui/Menu';
import Paper from '@material-hu/mui/Paper';
import Stack from '@material-hu/mui/Stack';

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

import Picker from './Picker';

export type PickerProps = MUIMenuProps;

const PickerWrapper = ({ children, ...rest }: PickerProps) => {
  return (
    <Menu
      anchorOrigin={{
        vertical: 'top',
        horizontal: 'right',
      }}
      transformOrigin={{
        vertical: 'bottom',
        horizontal: 'right',
      }}
      sx={{
        '& .MuiList-root': {
          p: 0,
        },
      }}
      {...rest}
      transitionDuration={0}
    >
      <Paper sx={{ maxWidth: 376, maxHeight: 360, overflowY: 'hidden' }}>
        {children}
      </Paper>
    </Menu>
  );
};

export type ReactionPickerProps = Pick<
  PickerProps,
  'anchorOrigin' | 'transformOrigin' | 'container'
> & {
  anchorEl: any;
  onClose?: (event: MouseEvent) => void;
  onSelect?: (emoji: string, unified: string, event: MouseEvent) => void;
};

const ReactionPicker = ({
  anchorEl,
  onClose = () => null,
  onSelect = () => null,
  anchorOrigin,
  transformOrigin,
  container,
}: ReactionPickerProps) => {
  const handleSelect = (emojiObject: EmojiClickData, event: MouseEvent) => {
    event.stopPropagation();
    onSelect(emojiObject.emoji, emojiObject.unified, event);
  };

  const handleClose = (event: MouseEvent) => {
    event.stopPropagation();
    onClose(event);
  };

  return (
    <PickerWrapper
      anchorEl={anchorEl}
      open={Boolean(anchorEl)}
      onClose={handleClose}
      anchorOrigin={anchorOrigin}
      transformOrigin={transformOrigin}
      container={container}
    >
      <Stack sx={{ '& .EmojiPickerReact .epr-category-nav': { py: 1 } }}>
        <Picker
          onEmojiClick={handleSelect}
          width={376}
          height={360}
        />
      </Stack>
    </PickerWrapper>
  );
};

export default ReactionPicker;
