import React, {FC, FormEvent, PropsWithChildren, ReactNode} from "react"
import ReactDOM from "react-dom"

export const Modal: FC<ModalProps> = ({children, show, closeModal, ...props}) => {

    const stopEvent = (event: FormEvent) => {
        event.stopPropagation()
        event.preventDefault()
    }

    return show && <Overlay onClick={closeModal}>
        <div className="dark:bg-gray-900 cursor-auto dark:text-white bg-white"
             onClick={stopEvent}
             {...props}>
            {children}
        </div>
    </Overlay>
}

interface ModalProps {
    children: ReactNode,
    show: boolean,
    closeModal: () => void
}

const Overlay: FC<OverlayProps> = ({children, ...props}) => {

    const app = document.getElementById('app')

    if (app) {
        return ReactDOM.createPortal(
            <button className={"flex justify-center items-center w-full fixed inset-0 z-10 bg-gray-900/50"}
                 {...props}>
                {children}
            </button>,
            app
        )
    }
}

interface OverlayProps {
    children: ReactNode,
    onClick: () => void
}
