/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useRef, useState } from 'react';
import { AppState, AppStateStatus } from 'react-native';

const getIsAppActive = (currentAppState: AppStateStatus) => {
  return currentAppState !== 'background' && currentAppState !== 'inactive';
};

const BACKGROUND_THRESHOLD = 30000; // 30 seconds in milliseconds

/*
 * This hook is used to check if the app is in the background for a long period of time.
 * If yes - returns true and trigger closing the bottomsheet.
 * If no - returns false and keep the bottomsheet open.
 *
 * Returns false unless background time is more than 30 seconds.
*/

export const useIsBackFromLongBackground = () => {
  const appState = useRef(AppState.currentState);
  const [isLongBackgroundTime, setIsLongBackgroundTime] = useState<boolean>(false);
  const backgroundTimestamp = useRef<number | null>(null);
  const activeTimestamp = useRef<number | null>(null);

  useEffect(() => {
    const subscription = AppState.addEventListener('change', nextAppState => {
      const nextAppStateActive = getIsAppActive(nextAppState);
      const currentAppStateActive = getIsAppActive(appState.current);

      if (!nextAppStateActive && currentAppStateActive) {
        // Set background timestamp when first entering background
        backgroundTimestamp.current = Date.now();
        activeTimestamp.current = null;
      } else if (nextAppStateActive && !currentAppStateActive) {
        // Set active timestamp when coming back from background
        activeTimestamp.current = Date.now();

        // Check if time difference is more than threshold
        if (activeTimestamp.current - (backgroundTimestamp.current ?? 0) > BACKGROUND_THRESHOLD) {
          setIsLongBackgroundTime(true);
        } else {
          setIsLongBackgroundTime(false);
        }

        // Reset timestamps for next cycle
        backgroundTimestamp.current = null;
        activeTimestamp.current = null;
      }

      appState.current = nextAppState;
    });

    return () => {
      subscription.remove();
    };
  }, []);

  return isLongBackgroundTime;
};
