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

function ModalContainer() {
  const { modal, setModal, position } = useModalStore();

  const divRef = useRef<HTMLDivElement>(null);
  const backdropRef = useRef<HTMLDivElement>(null);
  const modalRef = useRef<HTMLDivElement>(null);

  const isMobile = innerWidth < 640;

  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);
  }

  const handleDragEnd = (
    _event: MouseEvent | TouchEvent | PointerEvent,
    info: PanInfo
  ) => {
    // Закрываем модалку если свайпнули вниз больше чем на 100px или со скоростью > 500
    if (info.offset.y > 100 || info.velocity.y > 500) {
      setModal(null);
    }
  };

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

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

  return (
    <AnimatePresence>
      {modal && (
        <motion.div
          className="h-full fixed inset-0 z-[99999]"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
        >
          <div
            ref={modalRef}
            className={clsx(
              "bg-black/70 max-md:top-14 flex overflow-y-auto h-full w-full",
              isMobile ? "items-end" : "items-center",
              !isMobile &&
                (position === "center" ? "justify-center" : "justify-end")
            )}
          >
            <div className={clsx("max-h-full", isMobile && "w-full")}>
              <motion.div
                ref={divRef}
                className="2xl:p-[1.111vw]"
                initial={isMobile ? { y: "100%" } : undefined}
                animate={isMobile ? { y: 0 } : undefined}
                exit={isMobile ? { y: "100%" } : undefined}
                transition={{ bounce: 0, ease: "easeInOut" }}
                drag={isMobile ? "y" : false}
                dragConstraints={{ top: 0, bottom: 0 }}
                dragElastic={{ top: 0, bottom: 0.2 }}
                onDragEnd={isMobile ? handleDragEnd : undefined}
              >
                <div
                  ref={backdropRef}
                  className="absolute inset-0 cursor-pointer"
                  onClick={() => setModal(null)}
                />
                {modal}
              </motion.div>
            </div>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}

export default ModalContainer;
