import { Popover as OldPopover, PopoverProps, ConfigProvider } from 'antd';
import { getRenderPropValue } from 'antd/lib/_util/getRenderPropValue';
import React, { useContext, useEffect, useState } from 'react';
import './index.less';
import classNames from 'classnames';
import { AOP } from '../utils/AOP';

interface PopoverExtraProps {
  showCloseButton?: boolean;
}

const Popover = (props: PopoverProps & PopoverExtraProps) => {
  const { showCloseButton = false } = props;
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-popover');

  const [visible, setVisible] = useState(false);
  useEffect(() => {
    setVisible(props.visible);
  }, [props.visible]);

  // 拦截到visible的变化
  const onVisibleChange = new AOP<boolean, void>(props.onVisibleChange)
    .before((v) => {
      setVisible(v);
    })
    .getFunction();

  const CloseBtn = () => {
    return (
      <a
        onClick={() => {
          setVisible((v) => !v);
        }}
        className="close"
      >
        关闭
      </a>
    );
  };
  const newContent = (
    <div>
      <div className={!props.title && `${prefixCls}-content`}>
        {getRenderPropValue(props.content)}
      </div>
      <div style={{ display: 'flex', justifyContent: 'end' }}>
        {showCloseButton && <CloseBtn></CloseBtn>}
      </div>
    </div>
  );

  return (
    <div className={classNames(`${prefixCls}-box`)}>
      <OldPopover
        {...props}
        overlayClassName={classNames(
          `${prefixCls}-overlay`,
          props.overlayClassName,
        )}
        content={newContent}
        visible={visible}
        onVisibleChange={onVisibleChange}
      >
        {props.children}
      </OldPopover>
    </div>
  );
};

export { Popover };
