/* eslint-disable react-hooks/exhaustive-deps */
import clsx from "clsx";
import PopupHeader from "./PopupHeader";
import { useEffect, useState } from "react";
import { useRef } from "react";
import usePopupStore from "../store/popupStore";

interface PopupWrapperProps {
  children: React.ReactNode;
  className?: string;
  title?: string;
  leftButton?: React.ReactNode;
  draggable?: boolean;
}

function PopupWrapper({
  children,
  className,
  title,
  leftButton,
  draggable,
}: PopupWrapperProps) {
  const { position, setPosition } = usePopupStore();
  const [mouseDown, setMouseDown] = useState(false);
  const [mouseDownPosition, setMouseDownPosition] = useState(position);

  const wrapperRef = useRef<HTMLDivElement>(null);
  const headerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    addEventListener("mouseup", () => setMouseDown(false));
    return () => removeEventListener("mouseup", () => setMouseDown(false));
  }, []);

  function handleMouseMove(e: MouseEvent) {
    if (draggable && mouseDown && wrapperRef.current) {
      e.preventDefault();
      setPosition({
        x: Math.min(
          Math.max(0, position.x + e.clientX - mouseDownPosition.x),
          window.innerWidth - wrapperRef.current.clientWidth
        ),
        y: Math.min(
          Math.max(0, position.y + e.clientY - mouseDownPosition.y),
          window.innerHeight - wrapperRef.current.clientHeight
        ),
      });
      setMouseDownPosition({ x: e.clientX, y: e.clientY });
    }
  }

  useEffect(() => {
    addEventListener("mousemove", handleMouseMove);
    return () => removeEventListener("mousemove", handleMouseMove);
  }, [handleMouseMove]);

  useEffect(() => {
    if (headerRef.current) {
      headerRef.current.addEventListener("mousedown", (e) => {
        setMouseDown(true);
        setMouseDownPosition({ x: e.clientX, y: e.clientY });
      });
    }
    return () => {
      if (headerRef.current) {
        headerRef.current.removeEventListener("mousedown", (e) => {
          setMouseDown(true);
          setMouseDownPosition({ x: e.clientX, y: e.clientY });
        });
      }
    };
  }, []);

  return (
    <div
      ref={wrapperRef}
      className={clsx(
        "2xl:rounded-[2.222vw] rounded-[32px] relative bg-white shadow-[0_4px_40px_0_rgba(15,16,17,0.1)] overflow-hid den",
        className
      )}
    >
      <PopupHeader
        headerRef={headerRef}
        title={title}
        leftButton={leftButton}
        draggable={draggable}
      />
      <div className="2xl:p-[1.389vw] p-5">{children}</div>
    </div>
  );
}

export default PopupWrapper;
