/* eslint-disable react-hooks/exhaustive-deps */
import React, { useContext, useEffect, useState, useRef } from 'react';
import PropTypes from 'prop-types';
import isSticky from '~hooks/stickyOnScroll';
import { Context } from '~context/MainProvider';
import styles from './scroll-to-top.module.scss';

const ScrollToTop = ({ scrollTo = '0', offsetTop = 400, hideOnScrollDown = false }) => {
  const { cookieAccepted, bannerIsActive } = useContext(Context) || {};
  const [show, setShow] = useState(false);
  let scrollY = typeof window !== 'undefined' && (window?.scrollY || 0);
  const showScroll = isSticky(offsetTop);
  const scrollToTopBtn = useRef();

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

  const handleEvent = () => {
    if (window.scrollY > scrollY) {
      setShow(false);
    } else {
      setShow(true);
    }
    const scrollTopBtnHeight = parseInt(scrollToTopBtn.current.clientHeight / 2);
    const footerElementRect =
      document.querySelector('footer') && document.querySelector('footer').getBoundingClientRect();

    if (footerElementRect) {
      if (footerElementRect.y < window.innerHeight) {
        scrollToTopBtn.current.style.bottom = `${
          window.innerHeight - footerElementRect.y - scrollTopBtnHeight
        }px`;
      } else {
        scrollToTopBtn.current.style.bottom = '0px';
      }
    }

    scrollY = window.scrollY;
  };

  useEffect(() => {
    window.addEventListener('scroll', handleEvent);
    window.addEventListener('mousemove', handleEvent);
    window.addEventListener('touchstart', handleEvent);

    return () => {
      window.removeEventListener('scroll', handleEvent);
      window.removeEventListener('mousemove', handleEvent);
      window.removeEventListener('touchstart', handleEvent);
    };
  }, []);

  return (
    <button
      type="button"
      aria-label="Scroll to top"
      onClick={(e) => scrollTop(e)}
      ref={scrollToTopBtn}
      className={`${styles.scrollToTop || ''} ${cookieAccepted && (styles.cookieAccepted || '')} ${
        !bannerIsActive && (styles.closedBanner || '')
      } ${!show && hideOnScrollDown && (styles?.showScrollToTopButton || '')}`}
      style={{ display: showScroll ? 'flex' : 'none' }}
    />
  );
};

ScrollToTop.propTypes = {
  scrollTo: PropTypes.string,
  offsetTop: PropTypes.number,
  hideOnScrollDown: PropTypes.bool,
};

export default ScrollToTop;
