import { useState, useEffect } from 'react';
import { AppStateStatus, AppState } from 'react-native';

interface UseAppStateSettings {
  onChange?: (status: AppStateStatus) => void;
  onForeground?: () => void;
  onBackground?: () => void;
}

interface UseAppStateResult {
  appState: AppStateStatus;
}

export default function useAppState(
  settings?: UseAppStateSettings
): UseAppStateResult {
  const { onChange, onForeground, onBackground } = settings || {};
  const [appState, setAppState] = useState<AppStateStatus>(
    AppState.currentState
  );

  useEffect(() => {
    function handleAppStateChange(nextAppState: AppStateStatus) {
      if (nextAppState === 'active' && appState !== 'active') {
        if (onForeground) {
          onForeground();
        }
      } else if (
        appState === 'active' &&
        nextAppState.match(/inactive|background/)
      ) {
        if (onBackground) {
          onBackground();
        }
      }
      setAppState(nextAppState);
      if (onChange) {
        onChange(nextAppState);
      }
    }

    const appStateEvent = AppState.addEventListener(
      'change',
      handleAppStateChange
    );

    return () => {
      appStateEvent.remove();
    };
  }, [onChange, onForeground, onBackground, appState]);

  return { appState };
}
