import { useEffect, useState } from "react";

export function useContextMenu() {
  const [contextMenu, setContextMenu] = useState<React.ReactNode | undefined>();
  const [cursorPosition, setCursorPosition] = useState<[number, number]>([
    0, 0,
  ]);

  const setContextMenuState = (e: any, state: React.ReactNode) => {
    if (document.querySelector(`[data-radix-popper-content-wrapper]`)) return;

    setContextMenu(state);
    setCursorPosition([e.clientX, e.clientY]);
  };

  useEffect(() => {
    if (!contextMenu) return;

    const element = document.querySelector(".context-menu") as HTMLDivElement;

    if (!element) return;

    setTimeout(() => {
      element.style.setProperty("opacity", "1");
      element.style.setProperty(
        "top",
        cursorPosition[1] + element.clientHeight > window.innerHeight
          ? window.innerHeight - element.clientHeight - 10 + "px"
          : cursorPosition[1] + "px",
      );
      element.style.setProperty(
        "left",
        cursorPosition[0] + element.clientWidth > window.innerWidth
          ? window.innerWidth - element.clientWidth - 10 + "px"
          : cursorPosition[0] + "px",
      );
    }, 100);

    return () => {
      setContextMenu(undefined);
    };
  }, [contextMenu]);

  useEffect(() => {
    const handleClick = (e: any) => {
      if (
        e.target.getAttribute("[data-radix-popper-content-wrapper]") ||
        e.target.closest("[data-radix-popper-content-wrapper]")
      )
        return;

      setContextMenu(undefined);
    };

    window.addEventListener("click", handleClick);

    return () => {
      window.removeEventListener("click", handleClick);
    };
  }, []);

  return {
    contextMenu,
    setContextMenuState,
  };
}
