import React, { useEffect, useState } from 'react'
import { Popover } from 'react-tiny-popover'
import { EmojiSelectorProps, EmojiSelectorOpenButtonProps } from '../models'
import zocksStyle from './EmojiSelector.module.scss'
import { getClassName, getMergedClassNames } from '../../common'

export const EmojiSelector: React.FC<EmojiSelectorProps> = ({
  emojis,
  onSelectEmoji,
  currentMessage,
  components,
  styles,
}) => {
  const selectableEmojis = emojis ?? ['😂', '👍', '🎉', '😃', '👏']
  const popoverStyle = {
    zIndex: '1001',
    paddingBottom: '0.25rem',
  }

  const [isPopoverVisible, setPopoverVisible] = useState(false)

  useEffect(() => {
    if (!currentMessage) {
      setPopoverVisible(false)
    }
  }, [currentMessage])

  const mergedStyles = getMergedClassNames(zocksStyle, styles)

  const EmojiSelectorElement = () => (
    <div className={getClassName('emoji-selector__emoji-container', mergedStyles)}>
      {selectableEmojis.map((emoji, idx) => (
        <button
          key={idx}
          className={getClassName('emoji-selector__emoji-button', mergedStyles)}
          onClick={() => onSelectEmoji(emoji)}
          aria-label={`Insert ${emoji} emoji`}
        >
          {emoji}
        </button>
      ))}
    </div>
  )

  const OpenButtonElement = components?.OpenButton ?? EmojiSelectorDefaultOpenButton
  const openButtonClickHandler = () => setPopoverVisible(!isPopoverVisible)

  return (
    <Popover
      isOpen={isPopoverVisible}
      content={<EmojiSelectorElement />}
      onClickOutside={() => setPopoverVisible(false)}
      containerStyle={popoverStyle}
    >
      <OpenButtonElement onClick={openButtonClickHandler} styles={styles} />
    </Popover>
  )
}

const EmojiSelectorDefaultOpenButton: React.FC<EmojiSelectorOpenButtonProps> = React.forwardRef<
  HTMLButtonElement,
  EmojiSelectorOpenButtonProps
>(({ onClick, styles }, ref) => {
  const mergedStyles = getMergedClassNames(zocksStyle, styles)
  return (
    <button
      id='zocks__emoji-selector__open-button'
      ref={ref}
      className={getClassName('emoji-selector__open-button', mergedStyles)}
      onClick={onClick}
      aria-label='Toggle emoji selector'
    >
      <label htmlFor='zocks__emoji-selector__open-button'>😂</label>
    </button>
  )
})
