import { useEffect } from 'react';

const NOTISTACK_QUERY = '.notistack-SnackbarContainer';

type UseSnackbarPositionProps = {
  ref?: React.RefObject<HTMLDivElement>;
};

const useSnackbarPosition = ({ ref }: UseSnackbarPositionProps) => {
  let resizeObserver: ResizeObserver | null = null;

  useEffect(() => {
    const setupResizeObserver = (inputElement: HTMLElement) => {
      resizeObserver = new ResizeObserver(() => {
        const snackbarElement: HTMLElement | null =
          document.querySelector(NOTISTACK_QUERY);

        const rect = inputElement.getBoundingClientRect();
        const newBottomPosition = window.innerHeight - rect.top;

        if (snackbarElement) {
          snackbarElement.style.bottom = `${newBottomPosition}px`;
        }
      });

      resizeObserver.observe(inputElement);
    };

    if (ref?.current) {
      setupResizeObserver(ref.current);
    }

    return () => {
      const snackbarElement: HTMLElement | null =
        document.querySelector(NOTISTACK_QUERY);
      if (snackbarElement) {
        snackbarElement.style.bottom = '0px';
      }

      if (resizeObserver) {
        resizeObserver.disconnect();
      }
    };
  }, [ref]);
};

export default useSnackbarPosition;
