import _extends from "@babel/runtime/helpers/esm/extends";
import React, { forwardRef, useRef, cloneElement, useMemo, useCallback, useState, useEffect } from "react";
import createChainedFunction from "../../utils/createChainedFunction";
import useForkRef from "../../utils/useForkRef";
import { Overlay } from "../Overlay";
import { Window } from "../Window";
const getHasTransition = children => {
  return children.props ? Object.prototype.hasOwnProperty.call(children.props, "in") : false;
};
export const Modal = /*#__PURE__*/forwardRef((_ref, ref) => {
  let {
    children,
    disableFocusLock = false,
    disableScrollLock = false,
    disableBackgroundClick = false,
    disableBackgroundColor = false,
    disableCloseOnEsc = false,
    open: defaultOpen = false,
    onClose,
    onClickOutside,
    ...rest
  } = _ref;
  const [open, setOpen] = useState(defaultOpen);
  const [exited, setExited] = useState(true);
  const innerRef = useRef(null);
  const handleRef = useForkRef(innerRef, ref);
  const hasTransition = useMemo(() => {
    return getHasTransition(children);
  }, [children]);
  useEffect(() => {
    setOpen(defaultOpen);
  }, [defaultOpen]);
  const handleClose = useCallback(() => {
    setOpen(false);
    if (!hasTransition) {
      typeof onClose === "function" && onClose();
    }
  }, [hasTransition, onClose]);
  const handleBackgroundClick = useCallback(event => {
    if (!disableBackgroundClick) {
      event.preventDefault();
      return handleClose();
    }
    if (onClickOutside) {
      onClickOutside(event);
    }
  }, [disableBackgroundClick, onClickOutside, handleClose]);
  const handleEnter = useCallback(() => {
    setExited(false);
  }, []);
  const handleExited = useCallback(() => {
    setExited(true);
    typeof onClose === "function" && onClose();
  }, [onClose]);
  const childProps = useMemo(() => {
    let props = {};

    // It's a Transition like component
    if (hasTransition && children) {
      props = {
        onEnter: createChainedFunction(handleEnter, children.props.onEnter),
        onExited: createChainedFunction(handleExited, children.props.onExited),
        in: open
      };
    }
    return props;
  }, [children, handleEnter, handleExited, hasTransition, open]);
  if (!open && (!hasTransition || exited)) {
    return null;
  }
  return /*#__PURE__*/React.createElement(Window, _extends({}, rest, {
    ref: handleRef,
    onClose: handleClose,
    disableFocusLock: disableFocusLock,
    disableScrollLock: disableScrollLock,
    disableCloseOnEsc: disableCloseOnEsc
  }), open ? /*#__PURE__*/React.createElement(Overlay, {
    onClick: handleBackgroundClick,
    disableBackgroundColor: disableBackgroundColor
  }) : null, /*#__PURE__*/cloneElement(children, childProps));
});
Modal.displayName = "Modal";
//# sourceMappingURL=Modal.js.map