import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native'
import { Stack, useNavigationContainerRef } from 'expo-router'
import { StatusBar } from 'expo-status-bar'
import { Provider as StoreProvider } from 'react-redux'
import { MD3DarkTheme, MD3LightTheme, PaperProvider } from 'react-native-paper'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useReactNavigationDevTools } from '@dev-plugins/react-navigation'
import { useReactQueryDevTools } from '@dev-plugins/react-query'
import { useColorScheme } from '@/hooks/useColorScheme'
import store from '@/utils/store'
import { useStartBackgroundFetchServiceEffect } from '@/utils/background'
import { useStartGeolocationServiceEffect } from '@/utils/geolocation'
import LoginProvider from '@/components/LoginProvider'

const queryClient = new QueryClient()

export default function RootLayout() {
  useStartGeolocationServiceEffect()
  useStartBackgroundFetchServiceEffect()
  const colorScheme = useColorScheme()

  const navigationRef = useNavigationContainerRef()
  useReactNavigationDevTools(navigationRef)

  useReactQueryDevTools(queryClient)

  return (
    <StoreProvider store={store}>
      <QueryClientProvider client={queryClient}>
        <LoginProvider loginRedirect={'/login'}>
          <PaperProvider theme={colorScheme === 'dark' ? MD3DarkTheme : MD3LightTheme}>
            <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
              <Stack>
                <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
                <Stack.Screen name="login" options={{ headerShown: false }} />
                <Stack.Screen name="+not-found" />
              </Stack>
              <StatusBar style="auto" />
            </ThemeProvider>
          </PaperProvider>
        </LoginProvider>
      </QueryClientProvider>
    </StoreProvider>
  )
}
