import { ReactNode, useEffect } from 'react';
import { BackHandler } from 'react-native';
import { setIosSwipeGestureEnabled } from '../../native-modules/natives/setIosSwipeGestureEnabled';
import { useIsInitialScreen } from '../hooks/useIsInitialScreen';

export function CanGoBackGuard({
  children,
  canGoBack,
  onBack,
}: {
  canGoBack: boolean;
  children: ReactNode;
  onBack?: () => void;
}) {
  const isInitialScreen = useIsInitialScreen();
  const shouldBlockGoingBack = !canGoBack;

  useEffect(() => {
    if (!isInitialScreen || !canGoBack) {
      setIosSwipeGestureEnabled({ isEnabled: false });

      return () => {
        setIosSwipeGestureEnabled({ isEnabled: true });
      };
    }

    return;
  }, [canGoBack, isInitialScreen]);

  useEffect(() => {
    if (shouldBlockGoingBack) {
      const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
        onBack?.();
        return true;
      });

      return () => {
        subscription.remove();
      };
    }

    return;
  }, [shouldBlockGoingBack, onBack]);

  return <>{children}</>;
}
