/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect, useRef } from "react";
import useModalStore from "../store/modalStore";
import clsx from "clsx";

function ModalContainer() {
  const { modal, setModal, position } = useModalStore();
  const divRef = useRef<HTMLDivElement>(null);
  const backdropRef = useRef<HTMLDivElement>(null);
  const modalRef = useRef<HTMLDivElement>(null);

  function handleResize() {
    if (!modalRef.current) return;

    if (divRef.current!.clientHeight > modalRef.current!.clientHeight) {
      backdropRef.current!.style.height = `${divRef.current!.clientHeight}px`;
    } else {
      backdropRef.current!.style.height = `100%`;
    }
  }

  function handleKeydown(e: KeyboardEvent) {
    if (e.key !== "Escape") return;
    setModal(null);
  }

  useEffect(() => {
    window.addEventListener("resize", handleResize);
    window.addEventListener("keydown", handleKeydown);

    return () => {
      window.removeEventListener("resize", handleResize);
      window.removeEventListener("keydown", handleKeydown);
    };
  }, []);

  return (
    modal && (
      <div className="h-full">
        <div
          ref={modalRef}
          className={clsx(
            "bg-black/70 max-md:top-14 flex overflow-y-auto fixed inset-0 z-10 items-center",
            position === "center" ? "justify-center" : "justify-end"
          )}
        >
          <div className="max-h-full">
            <div ref={divRef} className="2xl:p-[1.111vw]">
              <div
                ref={backdropRef}
                className="absolute inset-0 cursor-pointer"
                onClick={() => setModal(null)}
              />
              {modal}
            </div>
          </div>
        </div>
      </div>
    )
  );
}

export default ModalContainer;
