import { useEffect, useRef, useState } from "react";
import { AppState, type AppStateStatus } from "react-native";
import { useMobileAuthStore } from "./useMobileAuth";

export default function useDeviceLock() {
	const [appState, setAppState] = useState<AppStateStatus>(
		AppState.currentState,
	);
	const appStateRef = useRef<AppStateStatus>(AppState.currentState);

	useEffect(() => {
		const subscription = AppState.addEventListener("change", (nextAppState) => {
			const previousAppState = appStateRef.current;

			const wasActive = previousAppState === "active";

			// if the we see aggressive locking then we should remove inactive.
			const isNowInactive =
				nextAppState === "background" || nextAppState === "inactive";

			if (wasActive && isNowInactive) {
				const auth = useMobileAuthStore.getState();

				if (auth.shouldLockForIdle()) {
					auth.lock();
				}
			}

			appStateRef.current = nextAppState;
			setAppState(nextAppState);
		});

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

	return appState;
}
