import classnames from 'classnames'
import React, { PureComponent } from 'react'
import ReactDOM from 'react-dom'
import { getIsPadDisplay } from '../utils'
import './index.less'
const noop = () => {}
interface Props {
  isPad?: boolean
  show: boolean
  onHide?: Function
}
interface State {
  show: boolean | null
}

class ShareNoticeComponent extends PureComponent<Props, State> {
  public state: State = {
    show: null
  }

  public componentWillUpdate(_: Props, state: State) {
    if (this.state.show !== false && state.show === false) {
      if (typeof this.props.onHide === 'function') {
        this.props.onHide()
      }
    }
  }

  public render() {
    const { isPad, show: propShow } = this.props
    if (!propShow) return ''
    const stateShow = this.state.show
    const show = typeof stateShow === 'object' && !stateShow ? true : stateShow
    return show ? (
      <div className="ph-share-notice" onClick={this.onClick.bind(this)}>
        'is-ipad': isPad
        <div className={classnames('ph-share-mark-img', {})} />
        <div
          className={classnames('ph-share-mark-texts', {
            'is-ipad': isPad
          })}
        >
          <p>点击右上角图标，</p>
          <p>选择分享到朋友圈</p>
        </div>
      </div>
    ) : (
      ''
    )
  }
  private onClick() {
    this.setState({
      show: false
    })
  }
}

export default class ShareNotice {
  public static show() {
    new ShareNotice().show()
  }
  public onHide: Function
  protected shareEl: HTMLDivElement | null = null
  protected propShow = true

  public constructor(onHide: Function = noop) {
    this.onHide = onHide
  }

  public show() {
    this.propShow = true
    const isPad: boolean = getIsPadDisplay()

    if (!this.shareEl) {
      this.shareEl = this.addNode(
        <ShareNoticeComponent
          isPad={isPad}
          show={this.propShow}
          onHide={this.removeNode.bind(this)}
        />
      )
    }
  }

  public hide() {
    if (!this.shareEl) return
    this.propShow = false
    if (typeof this.onHide === 'function') {
      this.onHide()
    }

    this.removeNode(false)
  }

  protected removeNode(callOnHide = true) {
    if (!this.shareEl) return
    if (callOnHide) {
      this.onHide()
    }
    // tslint:disable-next-line: no-non-null-assertion
    this.shareEl.parentNode!.removeChild(this.shareEl as Node)
    this.shareEl = null
  }

  protected addNode(element: JSX.Element) {
    const div = document.createElement('div')
    document.body.appendChild(div)
    ReactDOM.render(element, div)
    return div
  }
}
