import React, { useEffect } from 'react';

const Modal = ({
    isOpen,
    onClose,
    title,
    children,
    size = 'medium',
    showCloseButton = true,
    closeOnOverlayClick = true
}) => {
    useEffect(() => {
        if (isOpen) {
            document.body.style.overflow = 'hidden';
        } else {
            document.body.style.overflow = 'unset';
        }

        // Cleanup on unmount
        return () => {
            document.body.style.overflow = 'unset';
        };
    }, [isOpen]);

    useEffect(() => {
        const handleEscape = (e) => {
            if (e.key === 'Escape' && isOpen) {
                onClose();
            }
        };

        document.addEventListener('keydown', handleEscape);
        return () => document.removeEventListener('keydown', handleEscape);
    }, [isOpen, onClose]);

    if (!isOpen) return null;

    const handleOverlayClick = (e) => {
        if (e.target === e.currentTarget && closeOnOverlayClick) {
            onClose();
        }
    };

    const getModalClass = () => {
        const baseClass = 'proddisp-modal';
        switch (size) {
            case 'small':
                return `${baseClass} modal-small`;
            case 'large':
                return `${baseClass} modal-large`;
            case 'xlarge':
                return `${baseClass} modal-xlarge`;
            default:
                return `${baseClass} modal-medium`;
        }
    };

    return (
        <div className="proddisp-modal-overlay" onClick={handleOverlayClick}>
            <div className={getModalClass()}>
                <div className="modal-header">
                    <h2 className="modal-title">{title}</h2>
                    {showCloseButton && (
                        <button className="modal-close" onClick={onClose}>
                            <span className="dashicons dashicons-no-alt"></span>
                        </button>
                    )}
                </div>
                <div className="modal-content">
                    {children}
                </div>
            </div>
        </div>
    );
};

export default Modal;