import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
import { useFonts } from 'expo-font';
import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { StatusBar } from 'expo-status-bar';
import { useEffect, useState } from 'react';
import 'react-native-reanimated';
import { ThemedView } from '@/components/theme';
import { Session } from '@supabase/supabase-js';
import { useColorScheme } from '@/hooks/useColorScheme';
import { supabase } from '@/lib/supabase';
import Auth from '@/components/auth/Auth';
import PushNotificationManager from '@/services/PushNotificationManager';

// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();

const RootLayout = () => {
  const scheme = useColorScheme() ?? 'dark';
  const [session, setSession] = useState<Session | null>(null);

  const [loaded] = useFonts({
    SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
  });

  useEffect(() => {
    supabase.auth.getSession().then(({ data: { session } }) => {
      setSession(session);
    });

    supabase.auth.onAuthStateChange((_event, session) => {
      setSession(session);
    });
  }, []);

  useEffect(() => {
    if (loaded) {
      SplashScreen.hideAsync();
    }
  }, [loaded]);

  if (!loaded) {
    return null;
  }

  return (
    <PushNotificationManager>
      <ThemeProvider value={scheme === 'dark' ? DarkTheme : DefaultTheme}>
        {session && session.user ? (
          <Stack>
            <Stack.Screen name='(tabs)' options={{ headerShown: false }} />
            <Stack.Screen name='+not-found' />
          </Stack>
        ) : (
          <ThemedView style={{ flex: 1 }}>
            <Auth />
          </ThemedView>
        )}
        <StatusBar style='auto' />
      </ThemeProvider>
    </PushNotificationManager>
  );
};

export default RootLayout;
