import React, { useEffect, useRef } from 'react';

const GlobalModel = ({
  isOpen,
  closeModal,
  children,
  modalType = '',  // For custom positioning like modal-top, modal-bottom
  dialogClass = '',  // For additional custom classes on modal dialog
  role = 'dialog',   // Accessibility role for the modal
  size = '',         // Dynamically set the size (sm, lg, xl)
  dataAttributes = {}, // Additional dynamic data-bs-* attributes
  IsCloseBtn=true
}) => {
  const modalRef = useRef(null);  // Reference to the modal element

useEffect(() => {
  const modalElement = modalRef.current;
  const modalInstance = new window.bootstrap.Modal(modalElement, {
    backdrop: false,
  });

  if (isOpen) {
    modalInstance.show();
  } else {
    modalInstance.hide();
  }

  const handleHideModal = () => {
    closeModal();

    // ✅ FIX: Remove any lingering body classes/styles
    document.body.classList.remove('modal-open');
    document.body.style.overflow = '';
    document.body.style.paddingRight = '';
  };

  modalElement.addEventListener('hidden.bs.modal', handleHideModal);

  return () => {
    modalElement.removeEventListener('hidden.bs.modal', handleHideModal);

    // Also clean up just in case component unmounts
    document.body.classList.remove('modal-open');
    document.body.style.overflow = '';
    document.body.style.paddingRight = '';
  };
}, [isOpen, closeModal]);



  // Dynamically set the modal size classes (modal-sm, modal-lg, modal-xl)
  const modalSizeClass = size ? `modal-${size}` : '';  // Default is empty if no size is specified

  // Dynamically generate data-bs attributes
  const dataAttributesProps = Object.keys(dataAttributes).map(key => ({
    [key]: dataAttributes[key],
  } ) );
  


   // The gray background
    const backdropStyle = {
      position: 'fixed',
      top: 0,
      bottom: 0,
      left: 0,
      right: 0,
      backgroundColor: 'rgba(0,0,0,0.3)',
    };


  return (
    <div
      className={`modal fade ${ modalType }`} 
      id="customModal"
      tabIndex="-1"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
      ref={modalRef}  // Assign the ref to the modal element
      {...dataAttributesProps}
      style={backdropStyle}
    >
      <div className={`modal-dialog ${dialogClass} ${modalSizeClass } mx-sm-auto mx-1`} role={role} >
        <div className="modal-content">
          <div className="modal-header p-0">
            {/* Close button inside the modal header */}
           {IsCloseBtn && <button
              type="button"
              className="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
              onClick={closeModal}  // Trigger the React closeModal function
            ></button>}
          </div>
          <div className="modal-body  p-sm-4 p-0">
            {children}  {/* Render children here, which can be the ReportTask component */}
          </div>
        </div>
      </div>
    </div>
  );
};

export default GlobalModel;
