import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { forwardRef, useContext, useEffect, useImperativeHandle, useRef, useState } from 'react';
import cls from 'clsx';
import { createPopper, offsetModifier } from '@vant/popperjs';
import { extend, pick } from '../utils';
import { BORDER_BOTTOM } from '../utils/constant';
import useClickAway from '../hooks/use-click-away';
import Popup from '../popup';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
const popupProps = ['overlay', 'duration', 'overlayStyle', 'overlayClass', 'closeOnClickOverlay', 'teleport', 'onClose', 'onOpen', 'onClosed', 'onOpened', 'onClickOverlay'];
const Popover = forwardRef((_a, ref) => {
  var {
    children,
    className
  } = _a,
      props = __rest(_a, ["children", "className"]);

  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace('popover', prefixCls);
  const [visible, updateShow] = useState(false);
  const popper = useRef(null);
  const wrapperRef = useRef();
  const popoverRef = useRef();

  const createPopperInstance = () => createPopper(wrapperRef.current, popoverRef.current.popupRef.current, {
    placement: props.placement,
    modifiers: [{
      name: 'computeStyles',
      options: {
        adaptive: false,
        gpuAcceleration: false
      }
    }, extend({}, offsetModifier, {
      options: {
        offset: props.offset
      }
    })]
  });

  const updateLocation = () => {
    var _a;

    if (!visible) {
      return;
    }

    if (!popper.current) {
      popper.current = createPopperInstance();
    } else {
      (_a = popper.current) === null || _a === void 0 ? void 0 : _a.setOptions({
        placement: props.placement
      });
    }
  };

  const onClickWrapper = () => {
    if (props.trigger === 'click') {
      updateShow(!visible);
    }
  };

  const onClickAction = (action, index) => {
    var _a;

    if (action.disabled) {
      return;
    }

    (_a = props.onSelect) === null || _a === void 0 ? void 0 : _a.call(props, action, index);

    if (props.closeOnClickAction) {
      updateShow(false);
    }
  };

  const onClickAway = () => {
    if (props.closeOnClickOutside && (!props.overlay || props.closeOnClickOverlay)) {
      updateShow(false);
    }
  };

  const renderAction = (action, index) => {
    const {
      icon,
      text,
      color,
      disabled,
      className: actionClassname
    } = action;
    return _jsxs("div", Object.assign({
      className: cls(bem('action', {
        disabled,
        'with-icon': icon
      }), actionClassname),
      style: {
        color
      },
      onClick: () => onClickAction(action, index)
    }, {
      children: [icon ? React.cloneElement(icon, {
        className: cls(bem('action-icon'))
      }) : null, _jsx("div", Object.assign({
        className: cls(bem('action-text'), BORDER_BOTTOM)
      }, {
        children: text
      }))]
    }), index);
  };

  useEffect(() => {
    return () => {
      var _a;

      if (popper.current) {
        (_a = popper.current) === null || _a === void 0 ? void 0 : _a.destroy();
        popper.current = null;
      }
    };
  }, []);
  useEffect(() => {
    updateLocation();
  }, [visible, props.placement]);
  useEffect(() => {
    let popupTarget;

    const prevent = e => e.stopPropagation();

    if (popoverRef.current && popoverRef.current.popupRef.current) {
      popupTarget = popoverRef.current.popupRef.current;
      popupTarget.addEventListener('touchstart', prevent);
    }

    return () => {
      if (popupTarget) popupTarget.removeEventListener('touchstart', prevent);
    };
  }, [popoverRef.current]);
  useImperativeHandle(ref, () => ({
    show: () => {
      if (visible) {
        updateShow(false);
        setTimeout(() => updateShow(true), 0);
        return;
      }

      updateShow(true);
    },
    hide: () => updateShow(false)
  }));
  useClickAway(wrapperRef, onClickAway, 'touchstart');
  return _jsxs(_Fragment, {
    children: [_jsx("span", Object.assign({
      ref: wrapperRef,
      className: cls(bem('wrapper')),
      onClick: onClickWrapper
    }, {
      children: props.reference
    })), _jsxs(Popup, Object.assign({
      ref: popoverRef,
      visible: visible,
      className: cls(bem([props.theme])),
      position: "",
      transition: "rv-zoom",
      lockScroll: false
    }, pick(props, popupProps), {
      children: [_jsx("div", {
        className: cls(bem('arrow'))
      }), _jsx("div", Object.assign({
        role: "menu",
        className: cls(bem('content'))
      }, {
        children: children || props.actions.map(renderAction)
      }))]
    }))]
  });
});
Popover.defaultProps = {
  overlay: false,
  duration: 300,
  closeOnClickAction: true,
  closeOnClickOverlay: true,
  closeOnClickOutside: true,
  offset: [0, 8],
  theme: 'light',
  trigger: 'click',
  actions: [],
  placement: 'bottom'
};
export default Popover;