import * as React from "react";
import { Dialog as DialogPrimitive } from "radix-ui";
import { useControllableState } from "@radix-ui/react-use-controllable-state";

type DialogContextInterface = {
  open: boolean | undefined;
};

export const DialogContext = React.createContext({} as DialogContextInterface);

const NAME = "DialogRoot";

export type DialogRootProps = DialogPrimitive.DialogProps;

export const DialogRoot = ({
  open: openProp,
  defaultOpen,
  onOpenChange,
  ...props
}: DialogRootProps) => {
  const [open, setOpen] = useControllableState({
    prop: openProp,
    defaultProp: defaultOpen ?? false,
    onChange: onOpenChange,
  });
  return (
    <DialogContext.Provider
      value={{
        open,
      }}
    >
      <DialogPrimitive.Root
        open={open}
        onOpenChange={(val) => setOpen(val)}
        {...props}
      />
    </DialogContext.Provider>
  );
};

DialogRoot.displayName = NAME;
