import React, { useRef, useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import { Popover } from 'antd'
import DemioInput from '../DemioInput/DemioInput'
import EmojiPicker from '../EmojiPicker/EmojiPicker'
import DemioIcon from '../Icon/Icon'
import './DemioInputEmojiPicker.less'

function DemioInputEmojiPicker({ popoverProps, hideEmojiPicker, ...props }) {
  const inputRef = useRef()
  const [isEmojiPickerOpen, toggleEmojiPickerOpen] = useState(false)
  const [cursorPosition, setCursorPosition] = useState(0)

  const insertEmojiToText = (message, index, emoji) =>
    `${message.substring(0, index)}${emoji}${message.substring(index)}`

  const onEmojiSelect = ({ native }) => {
    const { onChange, maxLength } = props
    const input = inputRef?.current
    if (input) {
      const text = insertEmojiToText(input.value, input.selectionStart || 0, native)

      setCursorPosition((input.selectionStart || 0) + native.length)

      if (onChange && text.length <= maxLength) {
        onChange(text)
      }
    }
  }

  const addInputFocus = () => {
    if (inputRef?.current) {
      inputRef.current.focus()

      if (inputRef.current?.setSelectionRange) {
        setTimeout(
          (input) => {
            input.setSelectionRange(cursorPosition, cursorPosition)
          },
          0,
          inputRef.current
        )
      }
    }
  }

  // set cursor position after inserting emoji into a text
  useEffect(() => {
    if (cursorPosition) {
      addInputFocus()
    }
  }, [cursorPosition])

  useEffect(() => {
    if (isEmojiPickerOpen && document.activeElement !== inputRef.current) {
      inputRef.current.focus()
    }
  }, [isEmojiPickerOpen])

  return (
    <DemioInput
      ref={inputRef}
      // eslint-disable-next-line react/jsx-props-no-spreading
      {...props}
      addonComponent={
        hideEmojiPicker ? null : (
          <Popover
            trigger="click"
            arrowPointAtCenter
            visible={isEmojiPickerOpen}
            onVisibleChange={toggleEmojiPickerOpen}
            overlayClassName="EmojiPickerPopover"
            destroyTooltipOnHide
            placement="bottomRight"
            autoAdjustOverflow={false}
            // eslint-disable-next-line react/jsx-props-no-spreading
            {...popoverProps}
            content={
              <div className="EmojiPicker">
                <EmojiPicker onEmojiSelect={onEmojiSelect} />
              </div>
            }>
            <button type="button" className="Demio-Input-emoji-picker">
              <DemioIcon type="SmileEmoji" width={16} />
            </button>
          </Popover>
        )
      }
    />
  )
}

DemioInputEmojiPicker.propTypes = {
  onChange: PropTypes.func.isRequired,
  maxLength: PropTypes.number,
  popoverProps: PropTypes.shape({
    autoAdjustOverflow: PropTypes.bool,
    placement: PropTypes.string,
    destroyTooltipOnHide: PropTypes.bool,
    overlayClassName: PropTypes.string,
    arrowPointAtCenter: PropTypes.bool,
    trigger: PropTypes.string,
  }),
  hideEmojiPicker: PropTypes.bool,
}
DemioInputEmojiPicker.defaultProps = {
  maxLength: 524288,
  popoverProps: {},
  hideEmojiPicker: false,
}

export default DemioInputEmojiPicker
