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 'react-native-reanimated';
import { useColorScheme } from '@/hooks/useColorScheme';
import React, { useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import UserSelection from '@/components/UserSelection';
import { TouchableOpacity, Text } from 'react-native';

type User = {
  id: number;
  name: string;
  message: string;
};

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

export default function RootLayout() {
  const colorScheme = useColorScheme();
  const [loaded, error] = useFonts({
    SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
  });
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function prepare() {
      try {
        // Load the user
        const storedUser = await AsyncStorage.getItem('@user');
        if (storedUser) {
          setUser(JSON.parse(storedUser));
        }
      } catch (e) {
        console.error('Failed to load user', e);
      } finally {
        setIsLoading(false);
      }
    }

    prepare();
  }, []);

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

  const handleUserSelected = async (selectedUser: User) => {
    setUser(selectedUser);
    try {
      await AsyncStorage.setItem('@user', JSON.stringify(selectedUser));
    } catch (e) {
      console.error('Failed to save user', e);
    }
  };

  const handleSwitchUser = async () => {
    try {
      await AsyncStorage.removeItem('@user');
      setUser(null);
    } catch (e) {
      console.error('Failed to remove user', e);
    }
  };

  if (!loaded || isLoading) {
    return null; // or a loading indicator
  }

  if (!user) {
    return <UserSelection onUserSelected={handleUserSelected} />;
  }

  return (
    <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
      <Stack>
        <Stack.Screen 
          name="(tabs)" 
          options={{ 
            headerShown: true,
            title: user.name,
            headerRight: () => (
              <TouchableOpacity onPress={handleSwitchUser} style={{ marginRight: 15 }}>
                <Text style={{ color: colorScheme === 'dark' ? 'white' : 'black' }}>
                  Switch User
                </Text>
              </TouchableOpacity>
            ),
          }} 
        />
        <Stack.Screen name="+not-found" />
      </Stack>
    </ThemeProvider>
  );
}
