import { Stack, useSegments, useRouter } from 'expo-router';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { StatusBar } from 'expo-status-bar';
import React, { useEffect } from 'react';
import { ActivityIndicator, View } from 'react-native';
import { useDeepLinkHandler } from '../src/utils/deepLinks';
import { ThemeProvider, useTheme } from '../src/theme/ThemeContext';
import { useAuthStore } from '../src/store/authStore';
import { OfflineBanner } from '../src/components/OfflineBanner';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5 minutes
      retry: 2,
    },
  },
});

// Screens that are accessible without authentication
const PUBLIC_SCREENS = new Set(['login', 'register']);

function RootLayoutInner() {
  const { isDark } = useTheme();
  const { isLoading, isAuthenticated, loadUser } = useAuthStore();
  const segments = useSegments();
  const router = useRouter();

  // Initialize auth state on app start
  useEffect(() => {
    loadUser();
  }, [loadUser]);

  // Protected route logic: redirect to login if not authenticated
  useEffect(() => {
    if (isLoading) return;

    const currentRoute = segments[0];
    const isPublicRoute = PUBLIC_SCREENS.has(currentRoute);

    if (!isAuthenticated && !isPublicRoute) {
      router.replace('/login');
    } else if (isAuthenticated && (currentRoute === 'login' || currentRoute === 'register')) {
      router.replace('/(tabs)');
    }
    }, [isAuthenticated, isLoading, segments, router]);

  // Show a loading screen while auth is initializing
  if (isLoading) {
    return (
      <SafeAreaProvider>
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: isDark ? '#121212' : '#fff' }}>
          <StatusBar style={isDark ? 'light' : 'dark'} />
          <ActivityIndicator size="large" color="#4f46e5" />
        </View>
      </SafeAreaProvider>
    );
  }

  return (
    <SafeAreaProvider>
      <StatusBar style={isDark ? 'light' : 'dark'} />
      <OfflineBanner />
      <Stack
        screenOptions={{
          headerShown: false,
          animation: 'slide_from_right',
        }}
      >
        <Stack.Screen name="(tabs)" />
        <Stack.Screen
          name="login"
          options={{
            presentation: 'modal',
            animation: 'slide_from_bottom',
          }}
        />
        <Stack.Screen
          name="register"
          options={{
            presentation: 'modal',
            animation: 'slide_from_bottom',
          }}
        />
        <Stack.Screen
          name="tip-builder"
          options={{
            presentation: 'card',
            animation: 'slide_from_bottom',
          }}
        />
        <Stack.Screen
          name="tip-result"
          options={{
            presentation: 'card',
          }}
        />
        <Stack.Screen
          name="race-picker"
          options={{
            presentation: 'modal',
            animation: 'slide_from_bottom',
          }}
        />
        <Stack.Screen
          name="schedule-builder"
          options={{
            presentation: 'modal',
            animation: 'slide_from_bottom',
          }}
        />
        <Stack.Screen
          name="race/[id]"
          options={{
            presentation: 'card',
            animation: 'slide_from_right',
          }}
        />
      </Stack>
    </SafeAreaProvider>
  );
}

export default function RootLayout() {
  useDeepLinkHandler();

  return (
    <QueryClientProvider client={queryClient}>
      <ThemeProvider>
        <RootLayoutInner />
      </ThemeProvider>
    </QueryClientProvider>
  );
}
