import * as React from 'react'
import { createPortal } from 'react-dom';
import {Props, State} from './type'
import * as Styled from './style';

export class BackTop extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();

  watch = () => {
    let el = document.getElementById('viewport-left')
    let vwEl = document.getElementById('viewport')
    let top = vwEl.getBoundingClientRect().top
    let left = vwEl.getBoundingClientRect().left
    this.setState({
      viewportTop: top,
      viewportLeft: left
    })
    const config = { attributes: true, childList: true}
    const callback = (mutationList: any) => {
      mutationList.forEach((mutation: any) => {
        switch(mutation.type) {
          case 'childList':
            this.setState({
              viewportLeft: vwEl.getBoundingClientRect().left
            })
            break;
        }
      })
    }
    let observer = new MutationObserver(callback)
    observer.observe(el, config)
  }
  public componentDidMount() {
    this.updateBackTopView();
    window.addEventListener('scroll', this.updateBackTopView.bind(this))
    if (this.props.isEdit) {
      this.watch()
    }
  }

  public handleScrollTop() {
    window.scrollTo({
      left: 0,
      top: 0,
      behavior: 'smooth',
    });
  }

  public pageScrollTop() {
    if (document.scrollingElement) {
      return document.scrollingElement.scrollTop
    }

    return Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop)
  }

  public convertPxToRem(value: number) {
    return parseFloat((value / this.state.htmlFontSize).toFixed(2));
  }

  private updateBackTopView() {
    let scrollTopREM = this.convertPxToRem(this.pageScrollTop())
    // console.log(scrollTopREM, this.props.displayThreshold)
    if (scrollTopREM >= this.props.displayThreshold) {
      this.setState({
        show: true
      })
    } else {
      this.setState({
        show: false
      })
    }
  }

  public render() {
    const { icon, isEdit, imgStyle, style, left, top } = this.props;
    const { show, viewportTop, viewportLeft } = this.state;
    return (
      <Styled.BackTopContainer
        onClick={this.handleScrollTop.bind(this)}
        show={show}
        isEdit={isEdit}
        theme={{
          width: style.width,
          height: style.height,
          left: isEdit ? viewportLeft/37.5 + left : left,
          top: isEdit ? viewportTop/37.5 + top : top,
        }}>
        {icon && <img style={imgStyle} src={icon.url}/>}
      </Styled.BackTopContainer>
    )
  }
}