import React, { ReactNode, RefObject, useEffect, useRef } from 'react';
import { useElementOnScreen } from 'app/shared/hooks/useElementOnScreen';
import { getScreenWidth } from 'app/shared/store/ui/uiSelectors';
import { useSelector } from 'react-redux';

interface Props {
  children: ReactNode;
  sitckyDisplacement?: number;
  minimalScreenWidth?: number;
  onStickyToggle?: (isSticky: boolean)=>void
}

export const Sticky = ({ children, sitckyDisplacement, minimalScreenWidth, onStickyToggle }: Props) => {
  const childrenWrapperRef = useRef<HTMLDivElement>(null);
  const areChildrenOnScreen = useElementOnScreen(childrenWrapperRef as RefObject<HTMLDivElement>, sitckyDisplacement);
  const screenWidth = useSelector(getScreenWidth);
  
  let isSitckyDisabled = false;
  if (minimalScreenWidth) {
    isSitckyDisabled = screenWidth < minimalScreenWidth;
  }

  if (onStickyToggle) {
    useEffect(() => {
      onStickyToggle(!areChildrenOnScreen && !isSitckyDisabled);
    }, [ areChildrenOnScreen, isSitckyDisabled ]);
  }
  
  return (
    <>
      <div ref={childrenWrapperRef}>
        {children}
      </div>
      { !areChildrenOnScreen && !isSitckyDisabled && 
        <div className="c-sticky__content" style={{ width: childrenWrapperRef.current?.clientWidth, top: sitckyDisplacement }}>
          {children}
        </div>
      }
    </>
  );
};
