import React, { useState, useEffect } from 'react';
import BackToTopContainer from '@digigov/react-core/BackToTopContainer';
import BackToTopLink from '@digigov/react-core/BackToTopLink';
import { BaseProps } from '@digigov/react-core/Base';
export interface BackToTopProps extends BaseProps<'div'> {
  topLimitId?: string;
  onScrollToTop?: () => void;
}

const createObserver = (observeElement, callback) => {
  const intersectionObserver = new IntersectionObserver(
    ([e]) => {
      return callback(e.intersectionRatio < 1);
    },
    { threshold: [1] }
  );
  if (observeElement) {
    intersectionObserver.observe(observeElement);
  }
};

const useObserver = (id, callback) => {
  useEffect(() => {
    const el = document.getElementById(id);
    createObserver(el, callback);
  }, []);
};

export const BackToTop: React.FC<BackToTopProps> = React.forwardRef(
  function BackToTop({
    children,
    topLimitId = 'back-to-top-limit',
    onScrollToTop,
    ...props
  }) {
    const [persistent, setPersistent] = useState<boolean>(false);
    const callSetPersistent = (value) =>
      window.scrollY > 0 && setPersistent(value);
    useObserver(topLimitId, callSetPersistent);
    useObserver('back-to-top-element', callSetPersistent);

    return (
      <>
        <BackToTopContainer persistent={persistent} {...props}>
          <BackToTopLink
            id="back-to-top-link"
            onClick={onScrollToTop}
            href={`#${topLimitId}`}
          >
            {children}
          </BackToTopLink>
        </BackToTopContainer>
        <div id="back-to-top-element" />
      </>
    );
  }
);

export * from '@digigov/react-core/BackToTopLink';
export * from '@digigov/react-core/BackToTopLimit';
export * from '@digigov/react-core/BackToTopContainer';
export default BackToTopLink;
