import React, { FunctionComponent, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'

interface IModal {
  state: [boolean, Function]
  children?: any
}

const Modal: FunctionComponent<IModal> = ({ state, children }) => {
  const [visible, setVisible] = state
  const ref = useRef<undefined | HTMLElement>()

  useEffect(() => {
    ref.current = document.body
  }, [])

  const content = visible ? (
    <div className='modal'>
      <div className='container'>
        <button onClick={() => setVisible(false)} className='modal-close'>
          Close
        </button>
        {children}
      </div>
      <style jsx>{`
        .modal {
          position: absolute;
          top: 0;
          left: 0;
          height: 100vh;
          width: 100vw;
          background-color: #000000bb;
        }
        .modal > .container {
          margin: 2em auto;
          padding: 2em;
          background-color: #e0e0e0;
          max-width: 768px;
          width: 90vw;
          border-radius: 5px;
          box-shadow: 0px 0px 5px 5px #77777777;
        }
        .modal > .container > button.modal-close {
          float: right;
          padding: 0.3em 0.8em;
          border: none;
          color: white;
          background-color: black;
        }
      `}</style>
    </div>
  ) : null

  return ref.current ? createPortal(content, ref.current) : null
}

export default Modal
