import { useEffect, useRef, type ReactNode } from 'react'; import { createPortal } from 'react-dom'; import type { ReactElement } from 'react'; import { X } from 'lucide-react'; import { cn } from '@/lib/utils'; interface ModalProps { isOpen: boolean; onClose: () => void; title: string; description?: string; children: ReactNode; footer?: ReactNode; maxWidth?: 'sm' | 'md' | 'lg' | 'xl' | '2xl'; className?: string; showCloseButton?: boolean; preventCloseOnClickOutside?: boolean; } const maxWidthClasses = { sm: 'max-w-[400px]', md: 'max-w-[500px]', lg: 'max-w-[600px]', xl: 'max-w-[800px]', '2xl': 'max-w-[1000px]', }; export const Modal = ({ isOpen, onClose, title, description, children, footer, maxWidth = 'md', className, showCloseButton = true, preventCloseOnClickOutside = false, }: ModalProps): ReactElement | null => { const modalRef = useRef(null); // Handle click outside to close modal useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (preventCloseOnClickOutside) return; const target = event.target as HTMLElement; // Check if click is on dropdown menu (rendered via portal) const isDropdownClick = target.closest('[data-dropdown-menu="true"]'); // Only close if click is outside modal AND not on dropdown if (modalRef.current && !modalRef.current.contains(target) && !isDropdownClick) { onClose(); } }; if (isOpen) { document.addEventListener('mousedown', handleClickOutside); // Prevent body scroll when modal is open document.body.style.overflow = 'hidden'; } return () => { document.removeEventListener('mousedown', handleClickOutside); document.body.style.overflow = 'unset'; }; }, [isOpen, onClose, preventCloseOnClickOutside]); // Handle escape key useEffect(() => { const handleEscape = (event: KeyboardEvent) => { if (event.key === 'Escape' && isOpen && !preventCloseOnClickOutside) { onClose(); } }; document.addEventListener('keydown', handleEscape); return () => { document.removeEventListener('keydown', handleEscape); }; }, [isOpen, onClose, preventCloseOnClickOutside]); if (!isOpen) return null; const modalContent = (
{/* Modal Header */}

{title}

{description && (

{description}

)}
{showCloseButton && ( )}
{/* Modal Body - Scrollable */}
{children}
{/* Modal Footer */} {footer && (
{footer}
)}
); return createPortal(modalContent, document.body); };