import ReactDOM from 'react-dom'
import React, { Component } from 'react'

function isInsideElement (e1, e2) {
  if (e1 === null) {
    return false
  }
  return e1 === e2 || isInsideElement(e1.parentNode, e2)
}

export default (WrappedComponent) => class MTOutsideClickWithHiddenPropHoc extends Component {
  constructor (props) {
    super(props)
    this.state = {
      shouldHandleOutsideClick: undefined,
    }
    this._outsideClickListener = this._outsideClickListener.bind(this)
    this.listenForOutsideClick = this.listenForOutsideClick.bind(this)
    this.stopListenForOutsideClick = this.stopListenForOutsideClick.bind(this)
    this.setShouldHandleOutsideClickFn = this.setShouldHandleOutsideClickFn.bind(this)
  }

  UNSAFE_componentWillReceiveProps (nextProps) {
    if (nextProps.isHidden) {
      this.stopListenForOutsideClick()
    } else if (!nextProps.isHidden) {
      this.listenForOutsideClick()
    }
  }

  componentWillUnmount () {
    this.stopListenForOutsideClick()
  }

  setShouldHandleOutsideClickFn (fn) {
    this.setState({ shouldHandleOutsideClick: fn })
  }

  _outsideClickListener (e) {
    const { onOutsideClick } = this.props
    const { shouldHandleOutsideClick } = this.state
    // eslint-disable-next-line react/no-find-dom-node
    if (!isInsideElement(e.target, ReactDOM.findDOMNode(this))) {
      if (shouldHandleOutsideClick === undefined || shouldHandleOutsideClick(e)) {
        onOutsideClick()
      }
    }
  }

  listenForOutsideClick () {
    document.addEventListener('mousedown', this._outsideClickListener)
  }

  stopListenForOutsideClick () {
    document.removeEventListener('mousedown', this._outsideClickListener)
  }

  render () {
    const { isHidden } = this.props
    return (
      <WrappedComponent
        isHidden={ isHidden }
        setShouldHandleOutsideClickFn={ this.setShouldHandleOutsideClickFn }
        { ...this.props }
      />
    )
  }
}
