import { Component } from 'react';
import { createPortal } from 'react-dom';

interface IProps {
  opacity: number;
  root?: HTMLElement;
  onClose: () => void;
}

export class Portal extends Component<IProps> {
  div;
  container;
  root;
  constructor(props) {
    super(props);
    const { opacity = '0', top = '50%' } = props;

    this.div = document.createElement('div');
    this.div.style.top = top;
    this.div.style.left = '50%';
    this.div.style.position = 'absolute';
    this.div.style.transform = `translate(-50%, ${'top' in props ? 0 : '-50%'})`;

    this.container = document.createElement('div');
    this.container.style.position = 'fixed';
    this.container.style.width = '100%';
    this.container.style.height = '100%';
    this.container.style.left = '0';
    this.container.style.top = '0';
    this.container.style.zIndex = '20';
    this.container.style.background = `rgba(0,0,0,${opacity})`;
    this.container.appendChild(this.div);
    this.container.addEventListener('click', this.onClick);
    this.root = this.props.root || document.body;
  }
  componentDidMount() {
    document.body.appendChild(this.container);
    window.addEventListener('keydown', this.onEsc);
  }
  componentWillUnmount() {
    this.container.removeEventListener('click', this.onClick);
    document.body.removeChild(this.container);
    window.removeEventListener('keydown', this.onEsc);
  }

  onEsc = (e) => {
    // esc
    if (e.keyCode === 27) {
      const { onClose } = this.props;
      onClose && onClose();
    }
  };

  onClick = (e) => {
    const { onClose } = this.props;
    if (e.target === this.container && onClose) onClose();
  };

  render() {
    const { children } = this.props;
    return createPortal(children, this.div);
  }
}
