import { useEffect, useRef } from "react";

import createUseStyles from "./theme/createUseStyles";
import { cn } from "./util/cn";

const useStyles = createUseStyles(({ media }) => ({
  modal: {
    [media.md]: {
      padding: "var(--spacing-m) var(--spacing-xl)",
    },
  },
}));

export const MODAL_BACKDROP_TIMEOUT = 250;

export default function Modal({
  children,
  handleClose,
  isOpen,
}: React.PropsWithChildren<{
  handleClose: () => void;
  isOpen: boolean;
}>) {
  const classes = useStyles();

  const ref = useRef<HTMLDialogElement>(null);

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

  return (
    <dialog
      ref={ref}
      onCancel={handleClose}
      className={cn("overflow-auto justify-center items-center border-white bg-black py-xxl px-m shadow-none", classes.modal, {
        ["flex"]: isOpen,
      })}
    >
      {children}
    </dialog>
  );
}
