import * as React from 'react';
import * as equal from 'fast-deep-equal';
import {PureComponent, HTMLProps} from 'react';
import {Scrollbars as ReactCustomScrollbars} from 'react-custom-scrollbars';

export interface ScrollbarsProps extends HTMLProps<HTMLElement> {
  autoReset?: boolean;
}

export class Scrollbars extends PureComponent<ScrollbarsProps, {}> {
  private scrollbars: ReactCustomScrollbars;

  static defaultProps: ScrollbarsProps = {
    autoReset: false,
  };

  componentWillReceiveProps(nextProps: ScrollbarsProps) {
    if (nextProps.autoReset && !equal(nextProps.children, this.props.children)) {
      this.scrollbars.scrollToTop();
    }
  }

  render() {
    const {children, style} = this.props;

    return (
      <ReactCustomScrollbars
        autoHide
        ref={(instance) => this.scrollbars = instance}
        style={style}
      >
        {this.props.children}
      </ReactCustomScrollbars>
    );
  }

  scrollToTop() {
    this.scrollbars.scrollToTop();
  }
}
