import React, { useMemo } from 'react';
import { DialogProps } from '@radix-ui/react-dialog';
import { useControllableState } from '@radix-ui/react-use-controllable-state';

import { createContext } from '../utils/react';

export type DialogContextValues = {
  open: DialogProps['open'];
  setOpen: (value: DialogContextValues['open']) => void;
  modal: DialogProps['modal'];
};

const [DialogContext, useDialogContext] = createContext<DialogContextValues>(
  {
    open: undefined,
    setOpen: () => {},
    modal: true,
  },
  { name: 'DialogContext' },
);

interface DialogProviderProps
  extends Pick<DialogProps, 'open' | 'defaultOpen' | 'onOpenChange' | 'modal'> {
  children: React.ReactNode;
}

function DialogProvider({
  open: controlledOpen,
  defaultOpen,
  onOpenChange,
  modal = true,
  children,
}: DialogProviderProps) {
  const [open, setOpen] = useControllableState({
    prop: controlledOpen,
    defaultProp: defaultOpen,
    onChange: onOpenChange,
  });

  const contextValue = useMemo(
    () => ({
      open,
      setOpen,
      modal,
    }),
    [open, setOpen, modal],
  );

  return (
    <DialogContext.Provider value={contextValue}>
      {children}
    </DialogContext.Provider>
  );
}

export { DialogProvider, useDialogContext };
