import React, { forwardRef, memo, useLayoutEffect, useRef } from 'react'
import PropTypes from 'prop-types'
import cx from 'classnames'
import { identity, isNil, prop } from 'ramda'

const MTSelectSuggestion = memo(forwardRef((props, ref) => {
  const {
    suggestion,
    isActive,
    isDisabled = false,
    onSelect,
    SuggestionTemplate,
    isSelected,
    isMultiple,
    style,
    onHeightCalculated,
    className,
    ...otherProps
  } = props

  const itemRef = useRef(null)

  useLayoutEffect(() => {
    if (!isNil(onHeightCalculated)) {
      const node = itemRef.current
      const virtualNode = node.cloneNode(true)

      const {
        clientWidth: currentWidth,
      } = node

      // Clears the styles object to let the engine to calculate
      // the optimal size for the element
      virtualNode.style = {}

      // Changes the node's width to simulate the container environment
      virtualNode.style.width = `${currentWidth}px`

      // Hides the element so it's not visible while it's mounted
      virtualNode.style.position = 'absolute'
      virtualNode.style.visibility = 'hidden'
      virtualNode.style.top = 0
      virtualNode.style.left = 0
      virtualNode.style.zIndex = '-1'

      // Mounts the virtual node
      document.body.appendChild(virtualNode)

      const optimalHeight = prop('clientHeight', virtualNode)

      onHeightCalculated(optimalHeight)
      // Unmounts the virtual node
      return () => {
        virtualNode.parentNode.removeChild(virtualNode)
      }
    }
    return () => {}
  }, [])

  return (
    <div
      { ...otherProps }
      ref={ (_ref) => {
        itemRef.current = _ref
        ref?.(_ref)
      } }
      onClick={ isDisabled ? identity : onSelect }
      style={ style }
      className={ cx(
        'mt-select-suggestion',
        {
          'is-active': isActive,
          'is-selected': isSelected,
          'is-multiple': isMultiple,
          'is-disabled': isDisabled,
        },
        className
      ) }
    >
      <div className={ cx('mt-select-suggestion__icon', {
        checked: isSelected,
      }) }
      >
        <span className="mark" />
      </div>
      <SuggestionTemplate { ...suggestion } />
    </div>
  )
}))

{
  const {
    string,
    shape,
    bool,
    func,
    object,
  } = PropTypes

  MTSelectSuggestion.propTypes = {
    suggestion: shape({
      label: string.isRequired,
      id: string.isRequired,
    }).isRequired,
    isActive: bool,
    onSelect: func.isRequired,
    isSelected: bool,
    isMultiple: bool,
    // eslint-disable-next-line react/forbid-prop-types
    style: object,
    onHeightCalculated: func,
    SuggestionTemplate: func,
  }
}

MTSelectSuggestion.defaultProps = {
  isActive: false,
  isSelected: false,
  isMultiple: false,
  style: {},
  onHeightCalculated: null,
  SuggestionTemplate: prop('label'),
}

export default MTSelectSuggestion
