import { ReactNode, useEffect } from "react";
import styles from "./styles.module.css";

interface ModalProps {
  children: ReactNode;
  open?: boolean;
  isCloseButtonVisible?: boolean;
  className?: string;
  containerClassName?: string;
  type?: "hidden" | "normal";
  onClose?: () => void;
}

function Modal({
  open,
  children,
  isCloseButtonVisible = true,
  className = "",
  containerClassName = "",
  type = "normal",
  onClose,
}: ModalProps): JSX.Element {
  const handleClose = (event: React.MouseEvent) => {
    if (event.target !== event.currentTarget) return;
    document.body.classList.remove("no-scroll");
    onClose?.();
  };

  useEffect(() => {
    if (open) {
      document.body.classList.add("no-scroll");
    }

    return () => {
      document.body.classList.remove("no-scroll");
    };
  }, [open]);

  if (!open && type === "normal") return <></>;
  return (
    <div
      className={`${styles.modal} ${className} ${
        type === "hidden" && !open ? styles.hidden : ""
      }`}
      onClick={handleClose}
    >
      <div className={`${styles["modal-content"]} ${containerClassName}`}>
        {isCloseButtonVisible && (
          <button className={styles["modal-close-btn"]} onClick={handleClose} />
        )}
        {children}
      </div>
    </div>
  );
}

export default Modal;
