'use client';

import { ReactNode, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';

interface ModalProps {
  isOpen: boolean;
  onClose: () => void;
  title?: string;
  children: ReactNode;
  footer?: ReactNode;
  size?: 'sm' | 'md' | 'lg' | 'xl' | 'fullscreen';
  centered?: boolean;
  scrollable?: boolean;
  showCloseButton?: boolean;
  closeOnBackdrop?: boolean;
  closeButtonText?: string;
  className?: string;
  titleClassName?: string;
}

export default function Modal({
  isOpen,
  onClose,
  title,
  children,
  footer,
  size = 'md',
  centered = true,
  scrollable = false,
  showCloseButton = true,
  closeOnBackdrop = true,
  closeButtonText = 'Close',
  className = '',
  titleClassName = '',
}: ModalProps) {
  // Portal to document.body so the backdrop's `position: fixed` covers the
  // real viewport — rendered in place, a caller nested under any transformed
  // ancestor (sticky bars, animation wrappers) turns `fixed` into relative
  // positioning against that ancestor instead, leaving content outside it
  // (e.g. the sticky search bar) visibly undimmed. mounted guards against an
  // SSR document reference.
  const [mounted, setMounted] = useState(false);
  useEffect(() => {
    setMounted(true);
  }, []);

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
      document.body.style.paddingRight = '0px'; // Prevent layout shift
    }

    return () => {
      document.body.style.overflow = '';
      document.body.style.paddingRight = '';
    };
  }, [isOpen]);

  if (!isOpen || !mounted) return null;

  const handleBackdropClick = () => {
    if (closeOnBackdrop) {
      onClose();
    }
  };

  const sizeClass = {
    sm: 'modal-sm',
    md: '',
    lg: 'modal-lg',
    xl: 'modal-xl',
    fullscreen: 'modal-fullscreen-md-down',
  }[size];

  const dialogClasses = [
    'modal-dialog',
    sizeClass,
    centered && 'modal-dialog-centered',
    scrollable && 'modal-dialog-scrollable',
  ]
    .filter(Boolean)
    .join(' ');

  return createPortal(
    <>
      <div
        className={`modal fade show ${className}`}
        style={{
          padding: '0',
          display: 'block',
          position: 'fixed',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          zIndex: 1055,
        }}
        aria-modal="true"
        role="dialog"
      >
        <div className={dialogClasses}>
          <div className="modal-content webNewContent" style={{
            borderRadius: '0.5rem',
            position: 'relative',
            display: 'flex',
            flexDirection: 'column',
            width: '100%',
            pointerEvents: 'auto',
          }}>
            {/* Modal Header */}
            {(title || showCloseButton) && (
              <div className="modal-header bg-white">
                {title && <h5 className={`modal-title ${titleClassName}`}>{title}</h5>}
                {showCloseButton && (
                  <button
                    type="button"
                    className="btn-close rounded-circle"
                    onClick={onClose}
                    aria-label="Close"
                  />
                )}
              </div>
            )}

            {/* Modal Body */}
            <div className="modal-body bg-white px-0">{children}</div>

            {/* Modal Footer */}
            {footer && <div className="modal-footer bg-white">{footer}</div>}
          </div>
        </div>
      </div>

      {/* Backdrop */}
      <div
        className="modal-backdrop fade show"
        style={{
          position: 'fixed',
          top: 0,
          left: 0,
          width: '100vw',
          height: '100vh',
          zIndex: 1050,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
        }}
        onClick={handleBackdropClick}
      />
    </>,
    document.body
  );
}
