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
}) => {
  const modalRef = useRef(null);  // Reference to the modal element

  useEffect(() => {
    const modalElement = modalRef.current;
    const modalInstance = new window.bootstrap.Modal(modalElement);

    // Show modal if isOpen is true
    if (isOpen) {
      modalInstance.show();
    } else {
      modalInstance.hide();
    }

    // Handle modal hide event to invoke the closeModal function
    const handleHideModal = () => {
      closeModal();  // Close the modal via React state
    };

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

    return () => {
      modalElement.removeEventListener('hidden.bs.modal', handleHideModal);
    };
  }, [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],
  }));

  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}
    >
      <div className={`modal-dialog ${dialogClass} ${modalSizeClass}`} role={role}>
        <div className="modal-content">
          <div className="modal-header">
            {/* Close button inside the modal header */}
            <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">
            {children}  {/* Render children here, which can be the ReportTask component */}
          </div>
        </div>
      </div>
    </div>
  );
};

export default GlobalModel;
