import { useRef, useState } from 'react';

import { Stack } from '@mui/material';
import { IconMoodHappy } from '@tabler/icons-react';
import { type EmojiClickData } from 'emoji-picker-react';

import ActionButton from '../../components/ActionButton';
import { useTextArea } from '../../context';

import EmojiMenu from './menu';
import { type InsertEmojiProps } from './types';

const InsertEmoji = ({ title }: InsertEmojiProps) => {
  const { editor } = useTextArea();

  const anchorRef = useRef(null);
  const [open, setOpen] = useState(false);

  if (!editor) {
    return null;
  }

  const handleOpen = () => setOpen(true);

  const handleClose = (event: MouseEvent) => {
    event.preventDefault();
    event.stopPropagation();
    setOpen(false);
  };

  const handleSelect = (emojiData: EmojiClickData, event: MouseEvent) => {
    handleClose(event);
    editor.chain().focus().insertContent(emojiData.emoji).run();
  };

  return (
    <Stack>
      <ActionButton
        ref={anchorRef}
        title={title}
        icon={<IconMoodHappy />}
        onClick={handleOpen}
        isActive={false}
      />
      <EmojiMenu
        anchorRef={anchorRef}
        open={open}
        onClose={handleClose}
        onSelect={handleSelect}
      />
    </Stack>
  );
};

export default InsertEmoji;
