import React, { FunctionComponent, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { modal } from '../styles'

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}</style>
    </div>
  ) : null

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

export default Modal
