/* eslint-disable react-hooks/exhaustive-deps */
import { useIsFetching, useIsMutating } from '@tanstack/react-query';
import { useCallback, useEffect } from 'react';

import { useRouterListener } from '@/shared/lib/hooks';
import { addEventListeners, removeEventListeners } from './handle-event-listeners';

interface RouteChangeEffect {
  scrollTarget: React.MutableRefObject<HTMLElement | null>;
  onScroll: () => void;
  onTouchStart: () => void;
  onTouchMove: () => void;
  onTouchEnd: () => void;
  callback: () => void;
}

export const useRouteChangeEffect = ({
  scrollTarget,
  onScroll,
  onTouchStart,
  onTouchMove,
  onTouchEnd,
  callback,
}: RouteChangeEffect) => {
  const isFetching = useIsFetching();
  const isMutating = useIsMutating();
  const isLoading = isFetching > 0 || isMutating > 0;

  const resetScrollTarget = useCallback(() => {
    const rootEl = document.getElementById('root') as HTMLElement;
    const pullToRefreshEl = document.getElementsByClassName('ptr__children')[0] as HTMLElement;

    scrollTarget.current = rootEl;
    if (pullToRefreshEl?.scrollHeight > window.innerHeight) {
      scrollTarget.current = pullToRefreshEl;
      addEventListeners({ element: pullToRefreshEl, onScroll, onTouchStart, onTouchMove, onTouchEnd });
      removeEventListeners({ element: rootEl, onScroll, onTouchStart, onTouchMove, onTouchEnd });
    } else {
      addEventListeners({ element: rootEl, onScroll, onTouchStart, onTouchMove, onTouchEnd });
      removeEventListeners({ element: pullToRefreshEl, onScroll, onTouchStart, onTouchMove, onTouchEnd });
    }
  }, []);
  useEffect(() => {
    if (isLoading) return;
    resetScrollTarget();
  }, [isLoading]);

  useRouterListener(() => {
    setTimeout(() => {
      callback?.();
    }, 0);
  });
};
