import {Component} from 'react';
import PropTypes from 'prop-types';
import {ChevronUpIcon} from '@heroicons/react/solid';
import Button from './button';

class ScrollToTop extends Component {
  constructor(props) {
    super(props);
    this.state = {isVisible: false};
  }

  componentDidMount() {
    document.addEventListener('scroll', this.handleScrollEvent);
  }

  componentWillUnmount() {
    document.removeEventListener('scroll', this.handleScrollEvent);
  }

  handleScrollEvent = () => {
    this.setState({isVisible: window.pageYOffset > 300});
  };

  scrollToTop = () => {
    window.scrollTo({top: 0, behavior: 'smooth'});
  };

  render() {
    if (!this.state.isVisible) return null;

    return (
      <Button
        circular
        color='gray'
        colorWeight={400}
        size='lg'
        onClick={this.scrollToTop}
        className={`fixed bottom-${this.props.withFooter ? 16 : 5} left-5 rounded-full text-white`}
      >
        <ChevronUpIcon width={24} height={24}/>
      </Button>
    );
  }
}

ScrollToTop.defaultProps = {
  withFooter: false
};

ScrollToTop.propTypes = {
  withFooter: PropTypes.bool.isRequired
};

export default ScrollToTop;
