import React, { Component } from "react"
import PortalContent from "./Portal"

export interface IPortalProps {
  /**
   * 附加类名，此类名会增加到最外层的包含块上
   */
  className?: string
  /**
   * 当 Portal 的 children 被加入到 DOM 时的钩子
   */
  onChildrenMount?: () => void

  /**
   * children mounted to
   * @default document.body
   */
  container?: HTMLElement

  visible?: Boolean
}

class Portal extends Component<IPortalProps> {
  static displayName = "Portal"

  static defaultProps = {
    container: document?.body || null,
    onChildrenMount: () => {},
    visible: true,
  }

  instance: PortalContent | null

  componentWillUnmount() {
    this.instance = null
  }

  // eslint-disable-next-line consistent-return
  public componentDidMount = () => {
    const { container, onChildrenMount } = this.props
    if (!container) {
      return null
    }
    this.setState({}, onChildrenMount)
    // onChildrenMount()
  }

  render() {
    const { container, visible } = this.props
    return container || visible || this.instance ? (
      // eslint-disable-next-line no-return-assign
      <PortalContent ref={(ref) => (this.instance = ref)} {...this.props} />
    ) : null
  }
}

export default Portal
