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 { 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 AuthGate() {
  const { user, loading } = useAuth()
  const [initialRoute, setInitialRoute] = useState<'Login' | 'MainTabs' | null>(null)

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

  if (!initialRoute) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5F5F7' }}>
        <Text style={{ color: '#86868B' }}>加载中...</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>
        <NavigationContainer>
          <StatusBar barStyle="dark-content" background="#F5F5F7" />
          <AuthGate />
        </NavigationContainer>
      </AuthProvider>
    </SafeAreaProvider>
  )
}