import { type ParentProps, createEffect, onCleanup, onMount } from 'solid-js';
import { isServer } from 'solid-js/web';
import { Portal } from 'solid-js/web'; // Добавлен Portal
import { FaSolidX } from 'solid-icons/fa';

interface ModalProps extends ParentProps {
    isOpen: boolean;
    onClose: () => void;
    title?: string;
    size?: 'sm' | 'md' | 'lg' | 'xl';
}

const sizeClasses = {
    sm: 'max-w-md',
    md: 'max-w-lg',
    lg: 'max-w-2xl',
    xl: 'max-w-4xl',
};

export const SolidModal = (props: ModalProps) => {
    const sizeClass = sizeClasses[props.size ?? 'md'];

    const handleEscKey = (e: KeyboardEvent) => {
        if (e.key === 'Escape') {
            props.onClose();
        }
    };

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

    onMount(() => {
        if (!isServer) {
            document.addEventListener('keydown', handleEscKey);
        }
    });

    onCleanup(() => {
        if (!isServer) {
            document.removeEventListener('keydown', handleEscKey);
        }
    });

    createEffect(() => {
        if (!isServer) {
            if (props.isOpen) {
                document.body.style.overflow = 'hidden';
            } else {
                document.body.style.overflow = '';
            }
        }
    });

    return (
        <Portal>
            <div
                class={`fixed inset-0 z-[9999] flex items-center justify-center transition-opacity duration-300 ${
                    props.isOpen ? 'opacity-100 visible' : 'opacity-0 invisible'
                }`}
            >
                {/* Оверлей с обработчиком клика */}
                <div
                    class="absolute inset-0 bg-black/70 backdrop-blur-sm"
                    onClick={handleOverlayClick}
                ></div>
                <div
                    class={`relative bg-white rounded-xl shadow-2xl w-full ${sizeClass} max-h-[90vh] overflow-hidden transition-transform duration-300 ${
                        props.isOpen ? 'scale-100' : 'scale-95'
                    }`}
                    onClick={(e) => e.stopPropagation()} // Предотвращает закрытие при клике на модалку
                >
                    {props.title && (
                        <div class="flex items-center justify-between p-6 border-b border-gray-200">
                            <h3 class="text-lg font-semibold text-gray-900">{props.title}</h3>
                            <button
                                onClick={props.onClose}
                                class="flex items-center justify-center w-8 h-8 text-gray-500 hover:text-gray-700 transition-colors bg-gray-200 hover:bg-gray-300 rounded-full hover:cursor-pointer"
                                aria-label="Close modal"
                            >
                                <FaSolidX size={16} />
                            </button>
                        </div>
                    )}
                    {!props.title && (
                        <div class="absolute top-3 right-3">
                            <button
                                onClick={props.onClose}
                                class="flex items-center justify-center w-8 h-8 text-gray-500 hover:text-gray-700 transition-colors bg-gray-200 hover:bg-gray-300 rounded-full hover:cursor-pointer"
                                aria-label="Close modal"
                            >
                                <FaSolidX size={16} />
                            </button>
                        </div>
                    )}
                    <div class="p-6 overflow-y-auto max-h-[calc(90vh-100px)]">
                        {props.children}
                    </div>
                </div>
            </div>
        </Portal>
    );
};