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

type ScrollToTopProps = { withFooter?: boolean };
const initialState = { isVisible: false };
type ScrollToTopState = Readonly<typeof initialState>;

class ScrollToTop extends Component<ScrollToTopProps, ScrollToTopState> {
  readonly state: ScrollToTopState = initialState;

  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() {
    const { withFooter = false } = this.props;
    if (!this.state.isVisible) return null;

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

export default ScrollToTop;
