import type { ComponentChildren } from "preact";
import { useCallback, useEffect, useRef } from "preact/hooks";
import { X } from "lucide-preact";
import clsx from "clsx";

import styles from '../assets/modal.module.css';

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

export const Modal = ({ children, open, title, onClose, sidebar, footer, ['class']: cls, className }: IProps) => {
    const ref = useRef<HTMLDialogElement>(null);

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

    const handleBackdropMouseDown = useCallback((e: MouseEvent) => {
        if (e.target === ref.current) onClose?.();
    }, [onClose]);

    return (
        <dialog ref={ref} class={styles.dialog} onMouseDown={handleBackdropMouseDown}>
            <div class={clsx(styles.modal, cls ?? className)} onMouseDown={(e) => e.stopPropagation()}>
                {(title != null || onClose) && (
                    <div class={styles.header}>
                        {title && <h2 class={styles.title}>{title}</h2>}
                        {onClose && (
                            <button class={styles.closeButton} onClick={onClose}>
                                <X size={18} />
                            </button>
                        )}
                    </div>
                )}
                <div class={styles.body}>
                    {sidebar && <div class={styles.sidebar}>{sidebar}</div>}
                    <div class={styles.content}>{children}</div>
                </div>
                {footer && <div class={styles.footer}>{footer}</div>}
            </div>
        </dialog>
    );
};
