import { useVariants } from '../../variants';
import { ModalBackdrop } from './modal-backdrop';
import { ModalDialog, ModalDialogProps } from './modal-dialog';
import { ModalPortal, ModalPortalProps } from './modal-portal';
import { ModalProvider } from './modal.context';
import { modalVariants } from './modal.variants';

export type ModalProps = ModalPortalProps & ModalDialogProps & {
  onDismiss?: () => void;
  onConfirm?: () => void;
};

export function Modal({
  children,
  open,
  defaultOpen,
  onOpenChange: onOpenChange_,
  modal,
  forceMount,
  container,
  variant = 'default',
  variants,
  onDismiss: onDismiss_,
  onConfirm: onConfirm_,
  ...props
}: ModalProps) {
  const globalVariants = useVariants('modal', modalVariants);
  variants = variants || globalVariants;
  const onOpenChange = (open: boolean) => {
    if (!open && typeof onDismiss_ === 'function') {
      onDismiss_();
    }
    if (typeof onOpenChange_ === 'function') {
      onOpenChange_(open);
    }
  };
  const onConfirm = () => {
    if (typeof onConfirm_ === 'function') {
      onConfirm_();
    }
  };
  return (
    <ModalProvider value={{
      variant,
      variants,
      onConfirm,
    }}>
      <ModalPortal
        open={open}
        defaultOpen={defaultOpen}
        onOpenChange={onOpenChange}
        modal={modal}
        forceMount={forceMount}
        container={container}
      >
        <ModalBackdrop />
        <ModalDialog {...props} variant={variant} variants={variants}>
          {children}
        </ModalDialog>
      </ModalPortal>
    </ModalProvider>
  );
}
