import { KeyboardEvent, MouseEvent, ReactNode, useEffect, useRef } from "react";

import * as styles from "./modal.module.scss";

interface IModalProps {
  children: ReactNode;
  isOpen: boolean;
  className: string;
  onClose?: () => void;
}

export function Modal({ children, isOpen, className, onClose }: IModalProps) {
  const modalRef = useRef<HTMLDialogElement>(null);

  useEffect(() => {
    const modalElement = modalRef.current;
    if (!modalElement) return;

    if (isOpen) {
      modalElement.showModal();
    } else {
      modalElement.close();
    }
  }, [isOpen]);

  function handleClose() {
    onClose?.();
  }

  function onKeyDown(event: KeyboardEvent<HTMLDialogElement>) {
    if (event.key === "Escape") {
      handleClose();
    }
  }

  function onClick(event: MouseEvent<HTMLElement>) {
    if ((event.target as HTMLDialogElement)?.contains(modalRef.current)) {
      handleClose();
    }
  }

  return (
    <dialog ref={modalRef} onKeyDown={onKeyDown} onClick={onClick} className={`${styles.modal} ${className}`}>
      {children}
    </dialog>
  );
}
