import React, { memo, useEffect, useRef } from "react";
import { MdClose } from "react-icons/md";
import { StringCaser } from "Utils/utils";

const Modal = ({
  title,
  isOpen,
  zIndex,
  children,
  page = "",
  modalHeader,
  modalCloseClick,
  disableCancel = false,
  classes = { modal: "h-full", modalDialog: "h-[90%]", modalContent: "" },
}) => {
  const modalRef = useRef(null);

  // useEffect(() => {
  //   if (isOpen) {
  //     document.body.style.overflow = "hidden";
  //   } else {
  //     document.body.style.overflow = "auto";
  //   }
  // }, [isOpen]);

  useEffect(() => {
    const scrollableElements = document.querySelectorAll(
      "body, .scrollable-container" // Add other selectors if needed
    );

    if (isOpen) {
      scrollableElements.forEach((element) => {
        element.style.overflow = "hidden";
      });
    } else {
      scrollableElements.forEach((element) => {
        element.style.overflow = "auto";
      });
    }

    return () => {
      scrollableElements.forEach((element) => {
        element.style.overflow = "auto";
      });
    };
  }, [isOpen]);

  return (
    <div
      ref={modalRef}
      style={{
        zIndex: zIndex ?? 999999999999,
        backgroundColor: "rgba(0, 0, 0, 0.5)",
      }}
      className={`fixed bottom-0 left-0 right-0 top-0 flex w-full scale-0 items-center justify-center bg-[#00000099] p-[1.5rem] backdrop-blur-sm transition-all ${
        isOpen ? "scale-100" : "scale-0"
      } ${classes?.modal}`}
    >
      <div
        className={`border border-primary-black ${
          page === "ManagePermissionAddRole" ? "w-fit" : "w-[80%]"
        } relative overflow-auto rounded-lg bg-brown-main-bg pb-5 shadow ${
          classes?.modalDialog
        }`}
      >
        {modalHeader && (
          <div
            style={{
              zIndex: 1,
            }}
            className={`flex sticky inset-x-0 top-0 justify-between px-5 py-5 m-auto w-full border-b bg-brown-main-bg`}
          >
            <div className="text-center font-iowan text-[1.25rem] font-[700] capitalize leading-[1.5rem] tracking-[-1.5%]">
              {["string"].includes(typeof title)
                ? StringCaser(title, { casetype: "capitalize", separator: " " })
                : title}
            </div>
            {disableCancel ? null : (
              <button
                type="button"
                className="cursor-pointer modal-close"
                onClick={modalCloseClick}
              >
                <MdClose className="text-xl" />
              </button>
            )}
          </div>
        )}

        <div className={`-z-10 mt-4 px-5 ${classes?.modalContent}`}>
          {children}
        </div>
      </div>
    </div>
  );
};

const ModalMemo = memo(Modal);
export { ModalMemo as Modal };
