import {type ReactNode, type RefObject, useEffect, useRef} from "react";

export default function Dialog({
  open,
  close,
  classname,
  children,
}: {
  open: boolean;
  close: () => void;
  classname?: string;
  children: ReactNode;
}) {
  const ref: RefObject<HTMLDialogElement | null> = useRef(null);

  useEffect(() => {
    if (open) {
      ref.current?.showModal();
    } else {
      ref.current?.close();
    }
  }, [open]);

  function handleClickOutside(event: React.MouseEvent) {
    if (!ref.current) return;

    const dialogDimensions = ref.current.getBoundingClientRect()
    if (
      event.clientX < dialogDimensions.left ||
      event.clientX > dialogDimensions.right ||
      event.clientY < dialogDimensions.top ||
      event.clientY > dialogDimensions.bottom
    ) {
      close();
    }
  }

  return (
    <dialog
      ref={ref}
      onCancel={close}
      onPointerDown={handleClickOutside}
      className={classname}
    >
      {children}
    </dialog>
  );
}
