import React, { useEffect, useState } from 'react'
import { View, Text, StatusBar } from 'react-native'
import { NavigationContainer } from '@react-navigation/native'
import { createNativeStackNavigator } from '@react-navigation/native-stack'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import { AuthProvider, useAuth } from './src/components/AuthProvider'
import ThemeProvider, { useTheme } from './src/components/ThemeProvider'
import { getStoredToken } from './src/services/api'
import LoginScreen from './src/screens/LoginScreen'
import MainTabs from './src/navigation/MainTabs'
import type { RootStackParamList } from './src/navigation/types'

const RootStack = createNativeStackNavigator<RootStackParamList>()

function AppStatusBar() {
  const { isDark } = useTheme()
  return <StatusBar barStyle={isDark ? 'light-content' : 'dark-content'} background={isDark ? '#1C1C1E' : '#F5F5F7'} />
}

function AuthGate() {
  const { user, loading } = useAuth()
  const [initialRoute, setInitialRoute] = useState<'Login' | 'MainTabs' | null>(null)
  const { colors } = useTheme()

  useEffect(() => {
    if (!loading) {
      getStoredToken().then((token) => {
        setInitialRoute(token ? 'MainTabs' : 'Login')
      })
    }
  }, [loading])

  if (!initialRoute) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: colors.bg }}>
        <Text style={{ color: colors.textSecondary }}>加载中...</Text>
      </View>
    )
  }

  return (
    <RootStack.Navigator screenOptions={{ headerShown: false }}>
      <RootStack.Screen name="Login" component={LoginScreen} />
      <RootStack.Screen name="MainTabs" component={MainTabs} />
    </RootStack.Navigator>
  )
}

export default function App() {
  return (
    <SafeAreaProvider>
      <AuthProvider>
        <ThemeProvider>
          <NavigationContainer>
            <AppStatusBar />
            <AuthGate />
          </NavigationContainer>
        </ThemeProvider>
      </AuthProvider>
    </SafeAreaProvider>
  )
}