import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
// Copyright 1999-2021. Plesk International GmbH. All rights reserved.
import { disableDocumentScroll, enableDocumentScroll } from '../../utils';
import React, { Component, Fragment, createRef, isValidElement } from 'react';
import { safeInvoke } from '../utils';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { CLS_PREFIX, Z_INDEX_OVERLAY } from '../../constants';
import { CSSTransition } from 'react-transition-group';
import Backdrop from './Backdrop';
import Layer from '../Layer';
import FocusTrap from '../FocusTrap';

/**
 * `Overlay` component.
 */
const overlays = [];
/**
 * @since 0.0.65
 */

export default class Overlay extends Component {
  constructor(...args) {
    super(...args);

    _defineProperty(this, "state", {
      isOpened: false,
      isExist: false
    });

    _defineProperty(this, "prevFocusElement", null);

    _defineProperty(this, "contentRef", /*#__PURE__*/createRef());

    _defineProperty(this, "backdropRef", /*#__PURE__*/createRef());

    _defineProperty(this, "handleBackdropClick", () => {
      const {
        onClose,
        canCloseOnBackdropClick
      } = this.props;

      if (canCloseOnBackdropClick) {
        safeInvoke(onClose);
      } else {
        this.focus();
      }
    });

    _defineProperty(this, "handleContentKeyUp", e => {
      const {
        onClose
      } = this.props;

      if (!e.isDefaultPrevented() && e.key === 'Escape') {
        safeInvoke(onClose);
        e.preventDefault();
      }
    });
  }

  componentDidMount() {
    if (this.props.isOpen) {
      this.overlayWillOpen();
    }
  }

  componentDidUpdate(prevProps) {
    if (!this.props.isOpen && prevProps.isOpen) {
      this.overlayWillClose();
    } else if (this.props.isOpen && !prevProps.isOpen) {
      this.overlayWillOpen();
    }
  }

  componentWillUnmount() {
    if (this.props.isOpen) {
      this.overlayWillClose();
    }
  }

  overlayWillOpen() {
    disableDocumentScroll();
    overlays.push(this);
    this.setState({
      isExist: true
    }, () => {
      this.prevFocusElement = document.activeElement;
      this.setState({
        isOpened: true
      }, () => {
        this.focus();
      });
    });
  }

  overlayWillClose() {
    overlays.pop();

    if (overlays.length === 0) {
      enableDocumentScroll();
    }

    this.setState({
      isOpened: false
    }, () => {
      if (this.prevFocusElement) {
        this.prevFocusElement.focus();
        this.prevFocusElement = null;
      }
    });
  }

  focus() {
    if (this.contentRef.current === null || document.activeElement === null || !this.props.isOpen) {
      return;
    }

    const isFocusOutside = !this.contentRef.current.contains(document.activeElement);

    if (isFocusOutside) {
      const autofocusElement = this.contentRef.current.querySelector('[autofocus]');

      if (autofocusElement) {
        autofocusElement.focus();
      } else {
        this.contentRef.current.focus();
      }
    }
  }

  renderContent({
    baseClassName,
    children,
    canCloseOnEscapePress,
    sideBanner
  }) {
    return /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(CSSTransition, {
      in: this.state.isOpened,
      classNames: `${baseClassName}-`,
      timeout: 300,
      onExited: () => {
        this.setState({
          isExist: false
        });
      },
      nodeRef: this.contentRef
    }, /*#__PURE__*/React.createElement(FocusTrap, {
      className: `${baseClassName}__content`,
      onKeyUp: canCloseOnEscapePress ? this.handleContentKeyUp : null,
      ref: this.contentRef,
      role: "dialog",
      "aria-modal": "true"
    }, /*#__PURE__*/React.createElement("div", {
      className: `${baseClassName}__body`
    }, children), this.renderImage({
      baseClassName,
      image: sideBanner
    }))));
  }

  renderBackdrop({
    baseClassName
  }) {
    return /*#__PURE__*/React.createElement(CSSTransition, {
      in: this.state.isOpened,
      classNames: `${baseClassName}-`,
      timeout: 300,
      nodeRef: this.backdropRef
    }, /*#__PURE__*/React.createElement(Backdrop, {
      onClick: () => this.handleBackdropClick(),
      innerRef: this.backdropRef
    }));
  }

  renderImage({
    baseClassName,
    image
  }) {
    const classPrefix = `${baseClassName}__side`;

    if (!image) {
      return null;
    }

    if ( /*#__PURE__*/isValidElement(image)) {
      return /*#__PURE__*/React.createElement("div", {
        className: `${classPrefix}`
      }, image);
    }

    if (typeof image === 'string') {
      return /*#__PURE__*/React.createElement("div", {
        className: classPrefix
      }, /*#__PURE__*/React.createElement("img", {
        className: `${classPrefix}-image`,
        src: image
      }));
    }

    return /*#__PURE__*/React.createElement("div", {
      className: classPrefix
    }, /*#__PURE__*/React.createElement("img", _extends({
      className: `${classPrefix}-image`
    }, image)));
  }

  render() {
    const {
      baseClassName,
      className,
      children,
      isOpen,
      placement,
      size,
      sideBanner,
      sideBannerContainer,
      onClose,
      canCloseOnBackdropClick,
      canCloseOnEscapePress,
      style,
      ...props
    } = this.props;
    const {
      isExist
    } = this.state;

    if (!isExist) {
      return null;
    }

    return /*#__PURE__*/React.createElement(Layer, {
      level: Z_INDEX_OVERLAY
    }, /*#__PURE__*/React.createElement("div", _extends({
      className: classNames(baseClassName, `${baseClassName}--${placement}`, `${baseClassName}--${size}`, sideBanner && `${baseClassName}--side`, className),
      style: {
        '--sideBannerBackground': sideBannerContainer === null || sideBannerContainer === void 0 ? void 0 : sideBannerContainer.background,
        '--sideBannerAlign': sideBannerContainer === null || sideBannerContainer === void 0 ? void 0 : sideBannerContainer.align,
        ...style
      }
    }, props), this.renderBackdrop({
      baseClassName
    }), this.renderContent({
      baseClassName,
      children,
      canCloseOnEscapePress,
      sideBanner
    })));
  }

}

_defineProperty(Overlay, "propTypes", {
  /**
   * Toggles visibility.
   */
  isOpen: PropTypes.bool,

  /**
   * Overlay placement.
   */
  placement: PropTypes.oneOf(['center', 'left', 'right']),

  /**
   * Overlay size.
   */
  size: PropTypes.oneOf(['xs', 'sm', 'md', 'lg']),

  /**
   * onClose handler.
   */
  onClose: PropTypes.func,

  /**
   * Indicating if clicking the backdrop should close the overlay.
   */
  canCloseOnBackdropClick: PropTypes.bool,

  /**
   * Indicating if pressing the escape key should close the overlay.
   */
  canCloseOnEscapePress: PropTypes.bool,

  /**
   * Block with an image, placed at the side of the component
   * @since 3.25.0
   */
  sideBanner: PropTypes.oneOfType([PropTypes.string, PropTypes.object, PropTypes.element]),

  /**
   * Additional properties for the sideBanner
   * @since 3.25.0
   */
  sideBannerContainer: PropTypes.shape({
    /**
     * Values for css background property
     */
    background: PropTypes.string,

    /**
     * One of: center, flex-start, flex-end
     */
    align: PropTypes.oneOf(['center', 'flex-start', 'flex-end'])
  }),

  /**
   * @ignore
   */
  style: PropTypes.object,

  /**
   * Content of the `Overlay`.
   */
  children: PropTypes.node,

  /**
   * @ignore
   */
  className: PropTypes.string,

  /**
   * @ignore
   */
  baseClassName: PropTypes.string
});

_defineProperty(Overlay, "defaultProps", {
  isOpen: false,
  placement: 'center',
  size: 'md',
  onClose: null,
  canCloseOnBackdropClick: true,
  canCloseOnEscapePress: true,
  sideBanner: undefined,
  sideBannerContainer: undefined,
  style: undefined,
  children: null,
  className: null,
  baseClassName: `${CLS_PREFIX}overlay`
});