import clsx from "clsx";
import { Dialog } from "radix-ui";
import * as React from "react";
import { useEvent, useGetKey, useGetSet } from "../../hooks";
import * as styles from "./styles.module.css";

function block(e: Event) {
  e?.preventDefault();
}

export function Modal({
  children,
  className,
  onClose,
  modal = true,
  autoFocus = true,
  preview,
  ...rest
}: {
  className?: string;
  children: React.ReactNode;
  "data-id": string;
  preview?: true;
  modal?: boolean;
  autoFocus: boolean;
  onClose?: () => void;
}) {
  const key = useGetKey(rest);
  const [{ isOpen }, setState] = useGetSet(key, { isOpen: false }, true);
  const open = React.useCallback(() => {
    setState({ isOpen: true }, process.env.PREVIEW ? `onChange` : undefined);
  }, [setState]);
  const close = React.useCallback(() => {
    setState({ isOpen: false }, process.env.PREVIEW ? `onChange` : undefined);
  }, [setState]);
  const id = rest["data-id"];
  useEvent(id, "open", open);
  useEvent(id, "close", close);
  const additionalProps: Partial<
    React.ComponentPropsWithoutRef<typeof Dialog.Content>
  > = {};
  if (!autoFocus) {
    additionalProps.onOpenAutoFocus = block;
    additionalProps.onCloseAutoFocus = block;
    additionalProps.onPointerDownOutside = block;
    additionalProps.onInteractOutside = block;
  } else if (
    process.env.PREVIEW &&
    typeof document !== "undefined" &&
    document.body.classList.contains("__design")
  ) {
    additionalProps.onOpenAutoFocus = block;
    additionalProps.onCloseAutoFocus = block;
  }
  return (
    <Dialog.Root
      modal={modal}
      open={preview || isOpen}
      onOpenChange={(isOpen) => {
        setState({ isOpen }, process.env.PREVIEW ? `onChange` : undefined);
        if (isOpen == false) {
          onClose?.();
        }
      }}
    >
      <Dialog.Portal>
        <Dialog.Overlay className={styles.dialogOverlay} />
        <Dialog.Content
          className={clsx(styles.dialogContent, className)}
          aria-describedby={undefined}
          {...rest}
          {...additionalProps}
        >
          {children}
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}
