import { ReactNode, MouseEvent } from "react";
import { createPortal } from "react-dom";
import styles from "./modal.module.css";
import Button from "../button/button";

interface ModalProps {
    open: boolean;
    onClose: () => void;
    children: ReactNode;
    title?: string;
}

const Modal = ({ open, onClose, children, title }: ModalProps) => {
    if (!open) return null;

    const handleOverlayClick = () => {
        onClose();
    };

    const handleModalClick = (e: MouseEvent<HTMLDivElement>) => {
        e.stopPropagation();
    };

    return createPortal(
        <div className={styles.overlay} onClick={handleOverlayClick}>
            <div className={styles.modal} onClick={handleModalClick}>
                {title && <h2>{title}</h2>}
                {children}
                <div className={styles.modalFooter}>
                    <Button onClick={onClose}>Fermer</Button>
                </div>
            </div>
        </div>,
        document.body
    );
};

export default Modal;
