import React from "react";
import { Manager, Reference } from "react-popper";
import { OverlayLayer } from "./OverlayLayer";

export interface OverlayProps {
  /**
   * 参考的定位 DOM
   *
   * 需要通过提供的 `ref` 回调提供定位元素的 DOM Ref
   */
  children: (refHandler: React.Ref<any>) => JSX.Element;

  /**
   * 浮层列表，每一个都应该是一个 Overlay.Layer 实例
   * @docType React.ReactElement[]
   */
  layers: React.ReactElement[];
}

/**
 * 为定位元素创建一个覆盖层
 *
 * @example
 *
  ```js
  const [visible, setVisible] = useState(false);
  const open = () => setVisible(true);
  const close = () => setVisible(false);
  <Overlay
    layers={[
      <Overlay.Layer
        visible={visible}
        content={<div>我是浮层内容，<a onClick={close}>关闭</a></div>}
      />
    ]}
    children={ref => <a ref={ref} onClick={open}>点击弹出浮层</a>}
  />
  ```
 */
export function Overlay({ children, layers }: OverlayProps) {
  // 渲染定位组件
  return (
    <Manager>
      <Reference>{({ ref }) => children(ref)}</Reference>
      {layers}
    </Manager>
  );
}

Overlay.Layer = OverlayLayer;
Overlay.displayName = "Overlay";
