import { useFocusEffect } from '@react-navigation/native';
import { useRouter } from 'expo-router';
import { useAuth } from '@/src/contexts/AuthContext';
import { StorageServiceCasual } from 'common-ui';
import constants from '@/src/constants';

interface AuthenticatedRouteOptions {
  targetUrl?: string;
  queryParams?: Record<string, any>;
}

interface RedirectState {
  targetUrl: string;
  queryParams: Record<string, any>;
  timestamp: number;
}

export function useAuthenticatedRoute(options: AuthenticatedRouteOptions = {}) {
  const { isAuthenticated, isLoading } = useAuth();
  const router = useRouter();
  
  useFocusEffect(() => {
    // Don't redirect while auth is loading
    if (isLoading) return;

    // If user is authenticated, no need to do anything
    if (isAuthenticated) return;

    // User is not authenticated, store redirect state and navigate to login
    const redirectState: RedirectState = {
      targetUrl: options.targetUrl || '/',
      queryParams: options.queryParams || {},
      timestamp: Date.now(),
    };

    // Store the redirect state
    StorageServiceCasual.setItem(constants.AUTH_REDIRECT_KEY, JSON.stringify(redirectState))
      .then(() => {
        // Navigate to login page (push to keep original route in stack)
        router.push('/(auth)/login');
      })
      .catch((error) => {
        // Still navigate to login even if storage fails
        router.push('/(auth)/login');
      });
  });

  return {
    isAuthenticated,
    isLoading,
  };
}