import React, { useEffect, useRef, useState } from 'react';

export function TableFloatingScroll(props) {
  const ref = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLElement | null>(null);
  const scrollBlockRef = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(0);
  const [containerWidth, setContainerWidth] = useState(0);
  const [position, setPosition] = useState<'relative' | 'fixed'>('relative');
  useEffect(() => {
    const scrollBlockRefInstance = scrollBlockRef.current;
    contentRef.current = ref.current?.firstChild as HTMLElement;
    // @ts-ignore
    setContainerWidth(ref.current.offsetWidth);
    setWidth(contentRef.current.scrollWidth);
    const elementOffset =
      contentRef.current.offsetTop + contentRef.current.offsetHeight;
    function onBodyScroll() {
      const currentScroll = window.pageYOffset + window.innerHeight;
      if (
        currentScroll < elementOffset &&
        // @ts-ignore
        currentScroll > contentRef.current.offsetTop
      ) {
        setPosition('fixed');
      } else if (
        currentScroll >= elementOffset ||
        // @ts-ignore
        currentScroll <= contentRef.current.offsetTop
      ) {
        setPosition('relative');
      }
    }
    function onBlockScroll() {
      // @ts-ignore
      ref.current.scrollLeft = scrollBlockRefInstance.scrollLeft;
    }
    // @ts-ignore
    scrollBlockRefInstance.addEventListener('scroll', onBlockScroll);
    document.addEventListener('scroll', onBodyScroll);
    window.addEventListener('resize', () => {
      if (ref.current?.offsetWidth) {
        // @ts-ignore
        setContainerWidth(ref.current.offsetWidth);
      }
      if (contentRef.current?.offsetWidth) {
        // @ts-ignore
        setWidth(contentRef.current.scrollWidth);
      }
    });
    return () => {
      // @ts-ignore
      scrollBlockRefInstance.removeEventListener('scroll', onBlockScroll);
      document.removeEventListener('scroll', onBodyScroll);
    };
  }, []);
  return (
    <>
      <div
        ref={ref}
        style={{
          maxWidth: '100%',
          overflowX: 'scroll',
        }}
      >
        {props.children}
      </div>
      <div
        style={{
          overflow: 'auto',
          height: '35px',
          marginTop: '-35px',
          position: position,
          maxWidth: `${containerWidth}px`,
          bottom: 0,
        }}
        ref={scrollBlockRef}
      >
        <div style={{ width: `${width}px`, overflow: 'hidden' }}></div>
      </div>
    </>
  );
}
export default TableFloatingScroll;
