import '../global.css'
import 'react-native-reanimated'

import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native'
import * as Sentry from '@sentry/react-native'
import { Stack, useNavigationContainerRef } from 'expo-router'
import { StatusBar } from 'expo-status-bar'
import { useEffect } from 'react'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import { KeyboardProvider } from 'react-native-keyboard-controller'
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'

import { ModalPortal } from '@/@share/components'
import { HotUpdate } from '@/components/hot-update'
import { useColorScheme } from '@/hooks/use-color-scheme'
import { setupGlobalFetchLogger } from '@/lib/fetch-logger'
import { useUserSession } from '@/stores/UserStore'

Sentry.init({
  dsn: 'https://ef710a118839b1e86e38a3833a9a3c6c@o4507705403965440.ingest.us.sentry.io/4510576286302208',
  // Adds more context data to events (IP address, cookies, user, etc.)
  // For more information, visit: https://docs.sentry.io/platforms/react-native/data-management/data-collected/
  sendDefaultPii: true,
  enableLogs: true,
  // debug: true,
  enabled: !__DEV__, // 仅在生产环境启用 Sentry
})

// 目前无需求，先注释掉
// SplashScreen.preventAutoHideAsync()

// 全局启用 fetch 日志记录
if (__DEV__) {
  setupGlobalFetchLogger()
}

export const unstable_settings = {
  anchor: '(tabs)',
}

// 路由层
function RootLayout() {
  const ref = useNavigationContainerRef()

  useEffect(() => {
    if (!ref?.current) return

    const unsubscribe = ref.addListener('state', (e) => {
      const routes = e.data.state?.routes
      if (routes && routes.length > 0) {
        // Get the current active route
        const currentRoute = routes[routes.length - 1]

        // Extract the actual screen name from the route
        let screenName = currentRoute.name
        let params = currentRoute.params

        // Handle nested routes and get the actual screen name
        if (currentRoute.state?.routes) {
          const nestedRoutes = currentRoute.state.routes
          const activeNestedRoute = nestedRoutes[nestedRoutes.length - 1]
          if (activeNestedRoute && activeNestedRoute.name !== '__root') {
            screenName = activeNestedRoute.name
            params = activeNestedRoute.params
          }
        }

        console.warn(`screenName------------${screenName}, params ----------${JSON.stringify(params)}`)
      }
    })

    return unsubscribe
  }, [ref])

  return (
    <Providers>
      <Stack>
        <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
        <Stack.Screen name="auth" options={{ headerShown: false }} />
        <Stack.Screen name="forgot-password" options={{ headerShown: false }} />
        <Stack.Screen name="pointList" options={{ headerShown: false }} />
      </Stack>
    </Providers>
  )
}

function Providers({ children }: { children: React.ReactNode }) {
  const colorScheme = useColorScheme()
  useUserSession()

  return (
    <SafeAreaProvider>
      <GestureHandlerRootView style={{ flex: 1 }}>
        <KeyboardProvider>
          <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
            <SafeAreaView
              className="flex-1"
              edges={['top']}
              style={{ backgroundColor: colorScheme === 'dark' ? '#21221D' : '#ffffff' }}
            >
              <StatusBar />
              <HotUpdate />
              {children}
            </SafeAreaView>
            {/* modals */}

            {/* 挂载全局方法 */}
            <ModalPortal ref={(ref) => ((global as any).actionSheet = ref)} />
            <ModalPortal ref={(ref) => ((global as any).modal = ref)} />
            <ModalPortal ref={(ref) => ((global as any).loading = ref)} />
            <ModalPortal ref={(ref) => ((global as any).toast = ref)} />
          </ThemeProvider>
        </KeyboardProvider>
      </GestureHandlerRootView>
    </SafeAreaProvider>
  )
}

export default Sentry.wrap(RootLayout)
