import type { ComponentChildren } from "preact";
import { useCallback, useEffect, useRef } from "preact/hooks";

import styles from './Modal.module.css';

interface IProps {
    open: boolean;
    class?: string;
    className?: string;
    onClose?: () => void;
    children?: ComponentChildren;
}

export const Modal = ({ children, open, onClose, ['class']: cls, className }: IProps) => {
    const ref = useRef<HTMLDialogElement>(null);
    const handleClickWrapper = useCallback((e: MouseEvent) => {
        if (e.currentTarget instanceof HTMLDialogElement) {
            onClose?.();
        } else {
            e.stopPropagation();
        }
    }, [onClose]);

    useEffect(() => {
        if (open) {
            ref.current?.showModal();
        } else {
            ref.current?.close();
        }
    }, [open]);

    return (
        <dialog ref={ref} onMouseDown={handleClickWrapper} class={styles.dialog}>
            <div class={`${styles.content} ${cls ?? className ?? ''}`} onMouseDown={handleClickWrapper}>
                <div class={styles.close} onClick={onClose}>❌</div>
                {children}
            </div>
        </dialog>
    );
};
