import {JSX} from "preact";
import {createPortal} from "preact/compat";

type Props = {
    setModalOpen: (open: boolean) => never;
    title: string | JSX.Element;
    onSubmitText?: string;
    onSubmit?: () => void;
    children: string | JSX.Element | JSX.Element[] | (() => JSX.Element);
};

export const Modal = ({setModalOpen, title, onSubmit, onSubmitText, children}: Props) => {
    const body = document.querySelector("body");

    return createPortal(
        <div class="modal is-active">
            <div
                class="modal-background"
                onClick={() => {
                    setModalOpen(false);
                }}
            ></div>
            <div class="modal-card">
                <header class="modal-card-head">
                    <label class="modal-card-title">{title}</label>
                    <button
                        class="delete close-modal"
                        aria-label="close"
                        onClick={() => {
                            setModalOpen(false);
                        }}
                    ></button>
                </header>
                <section class="modal-card-body">{children}</section>
                {onSubmit && (
                    <footer class="modal-card-foot">
                        <button class="button is-success" onClick={onSubmit}>
                            {onSubmitText || "Save"}
                        </button>
                        <button
                            class="button close-modal"
                            onClick={() => {
                                setModalOpen(false);
                            }}
                        >
                            Cancel
                        </button>
                    </footer>
                )}
            </div>
            <button
                class="modal-close is-large close-modal"
                aria-label="close"
                onClick={() => {
                    setModalOpen(false);
                }}
            ></button>
        </div>,
        body,
    );
};
