import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/* eslint-disable no-plusplus */

import { useMemo, useState, useEffect, useRef, forwardRef, useImperativeHandle, useContext } from 'react';
import clsx from 'clsx';
import { CSSTransition } from 'react-transition-group';
import { Cross } from '@react-vant/icons';
import Overlay from '../overlay';
import useEventListener from '../hooks/use-event-listener';
import { isDef } from '../utils';
import { callInterceptor } from '../utils/interceptor';
import { renderToContainer } from '../utils/dom/renderToContainer';
import useSsrCompat from '../hooks/use-ssr-compat';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
import PopupContext from './PopupContext';
import { useLockScroll } from '../hooks/use-lock-scroll';
export const sharedPopupProps = ['round', 'zIndex', 'closeable', 'overlay', 'overlayClass', 'overlayStyle', 'destroyOnClose', 'forceRender', 'lockScroll', 'duration', 'transition', 'closeOnClickOverlay', 'closeOnPopstate', 'onClickOverlay', 'safeAreaInsetBottom', 'onOpen', 'onClose', 'onOpened', 'onClosed', 'beforeClose'];
let globalZIndex = 2000;
const Popup = forwardRef((props, ref) => {
  var _a;

  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace('popup', prefixCls);
  const {
    round,
    visible,
    closeable,
    title,
    descrition,
    children,
    duration,
    closeIcon,
    position
  } = props;
  const opened = useRef(false);
  const zIndex = useRef((_a = props.zIndex) !== null && _a !== void 0 ? _a : globalZIndex);
  const popupRef = useRef();
  const [animatedVisible, setAnimatedVisible] = useState(visible);
  const [ssrCompatRender, rendered] = useSsrCompat();
  const style = useMemo(() => {
    const initStyle = Object.assign({
      zIndex: zIndex.current
    }, props.style);

    if (isDef(props.duration)) {
      const key = props.position === 'center' ? 'animationDuration' : 'transitionDuration';
      initStyle[key] = `${props.duration}ms`;
    }

    return initStyle; // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [zIndex.current, props.position, props.style, props.duration]);

  const open = () => {
    var _a;

    if (props.zIndex !== undefined) {
      zIndex.current = +props.zIndex;
    } else {
      zIndex.current = globalZIndex++;
    }

    opened.current = true;
    (_a = props.onOpen) === null || _a === void 0 ? void 0 : _a.call(props);
  };

  const close = () => {
    if (opened.current) {
      callInterceptor({
        interceptor: props.beforeClose,
        args: ['close'],
        done: () => {
          var _a;

          opened.current = false;
          (_a = props.onClose) === null || _a === void 0 ? void 0 : _a.call(props);
        }
      });
    }
  };

  const onClickOverlay = event => {
    var _a;

    (_a = props.onClickOverlay) === null || _a === void 0 ? void 0 : _a.call(props, event);

    if (props.closeOnClickOverlay) {
      close();
    }
  };

  const renderOverlay = () => {
    if (props.overlay) {
      return _jsx(Overlay, {
        visible: visible && rendered,
        className: props.overlayClass,
        customStyle: props.overlayStyle,
        zIndex: zIndex.current,
        duration: duration,
        onClick: onClickOverlay
      });
    }

    return null;
  };

  const onClickCloseIcon = e => {
    if (props.onClickCloseIcon) {
      props.onClickCloseIcon(e);
    }

    close();
  };

  const renderCloseIcon = () => {
    if (closeable) {
      const {
        closeIconPosition
      } = props;

      if (closeIcon) {
        return _jsx("div", Object.assign({
          className: clsx(bem('close-icon', closeIconPosition)),
          onClick: onClickCloseIcon
        }, {
          children: closeIcon
        }));
      }

      return null;
    }

    return null;
  };

  const renderTitle = () => {
    if (title) {
      return _jsx("div", Object.assign({
        className: clsx(bem('title'))
      }, {
        children: title
      }));
    }

    return null;
  };

  const renderDescrition = () => {
    if (descrition) {
      return _jsx("div", Object.assign({
        className: clsx(bem('descrition'))
      }, {
        children: descrition
      }));
    }

    return null;
  };

  const renderPopup = () => {
    const {
      safeAreaInsetBottom
    } = props;
    return _jsxs("div", Object.assign({
      ref: popupRef,
      style: Object.assign(Object.assign({}, style), {
        display: !visible && !animatedVisible ? 'none' : undefined
      }),
      className: clsx(bem({
        round,
        [position]: position
      }), {
        'rv-safe-area-bottom': safeAreaInsetBottom
      }, props.className),
      onClick: props.onClick
    }, {
      children: [renderTitle(), renderDescrition(), children, renderCloseIcon()]
    }));
  };

  const renderTransition = () => {
    const {
      transition,
      destroyOnClose,
      forceRender
    } = props;
    const name = position === 'center' ? `${prefixCls}-fade` : `${prefixCls}-popup-slide-${position}`;
    return _jsx(CSSTransition, Object.assign({
      in: visible && rendered,

      /**
       * https://github.com/reactjs/react-transition-group/pull/559
       */
      nodeRef: popupRef,
      timeout: duration,
      classNames: transition || name,
      mountOnEnter: !forceRender,
      unmountOnExit: destroyOnClose,
      onEnter: open,
      onEntered: props.onOpened,
      onExited: () => {
        var _a;

        setAnimatedVisible(false);
        (_a = props.onClosed) === null || _a === void 0 ? void 0 : _a.call(props);
      }
    }, {
      children: renderPopup()
    }));
  };

  useEventListener('popstate', () => {
    if (props.closeOnPopstate) {
      close();
    }
  });
  useEffect(() => {
    if (!rendered) return;

    if (visible) {
      setAnimatedVisible(true);
    }
  }, [visible, rendered]);
  useLockScroll(popupRef, visible && props.lockScroll);
  useImperativeHandle(ref, () => ({
    popupRef
  }));
  return ssrCompatRender(() => renderToContainer(props.teleport, _jsxs(PopupContext.Provider, Object.assign({
    value: {
      visible
    }
  }, {
    children: [renderOverlay(), renderTransition()]
  }))));
});
Popup.defaultProps = {
  duration: 300,
  overlay: true,
  lockScroll: true,
  position: 'center',
  closeIcon: _jsx(Cross, {}),
  closeIconPosition: 'top-right',
  closeOnClickOverlay: true,
  teleport: () => document.body
};
export default Popup;