import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
import { HotKeys } from 'react-hotkeys'
import styled from 'styled-components'

const ModalContainer = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: transparent;
  opacity: ${props => props.visible ? 1 : 0};
  pointer-events: ${props => props.visible ? 'all' : 'none'};
`

class ModalBlur extends React.PureComponent {
  static propTypes = {
    children: PropTypes.oneOfType([
      PropTypes.node,
      PropTypes.string
    ]),
    visible: PropTypes.bool,
    closeKeys: PropTypes.arrayOf(PropTypes.string),
    onRequestToClose: PropTypes.func,
    cancellable: PropTypes.bool
  }

  static defaultProps = {
    children: null,
    visible: false,
    closeKeys: ['esc'],
    onRequestToClose: null,
    cancellable: false
  }

  get keysActions() {
    return {
      requestToClose: this.props.closeKeys
    }
  }

  get keysHandlers() {
    return {
      requestToClose: (event) => {
        const { cancellable, onRequestToClose } = this.props
        !cancellable && onRequestToClose && onRequestToClose()
      }
    }
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.visible !== this.props.visible) {
      document.querySelector('#root').style.filter =
        this.props.visible ? 'blur(5px)' : null
    }
  }

  render () {
    const autofocus = el => el && el.parentNode.focus()

    return ReactDOM.createPortal(
      <HotKeys keyMap={this.keysActions} handlers={this.keysHandlers}>
        <ModalContainer
          innerRef={autofocus}
          visible={this.props.visible}
        >
          {this.props.children}
        </ModalContainer>
      </HotKeys>,
      document.body
    )
  }
}

export default ModalBlur
