import { jsx as _jsx } from "react/jsx-runtime";
import { useContext, useRef } from 'react';
import { CSSTransition } from 'react-transition-group';
import clsx from 'clsx';
import { isDef, preventDefault } from '../utils';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
import { useEventListener } from '../hooks';

const Overlay = props => {
  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace('overlay', prefixCls);
  const nodeRef = useRef(null);
  const {
    visible,
    duration
  } = props;

  const preventTouchMove = event => {
    if (!props.lockScroll) return;
    preventDefault(event, true);
  };

  const renderOverlay = () => {
    const style = Object.assign(Object.assign({
      zIndex: props.zIndex !== undefined ? +props.zIndex : undefined,
      touchAction: props.lockScroll && 'none'
    }, props.style), props.customStyle);

    if (isDef(duration)) {
      style.animationDuration = `${duration}ms`;
    }

    return _jsx("div", Object.assign({
      ref: nodeRef,
      style: style,
      onClick: props.onClick,
      className: clsx(bem(), props.className)
    }, {
      children: props.children
    }));
  };

  useEventListener('touchmove', preventTouchMove, {
    target: nodeRef
  });
  return _jsx(CSSTransition, Object.assign({
    nodeRef: nodeRef,
    mountOnEnter: true,
    unmountOnExit: true,
    in: visible,
    timeout: duration,
    classNames: `${prefixCls}-fade`
  }, {
    children: renderOverlay()
  }));
};

Overlay.defaultProps = {
  lockScroll: true,
  duration: 300
};
export default Overlay;