import { ThemedView } from '@/components/ThemedView';
import { ROUTES } from '@/constants/Routes';
import { usePushNotifications } from '@/hooks/usePushNotifications';
import { useThemeColor } from '@/hooks/useThemeColor';
import { preloadUserData } from '@/store/userSlice';
import { router } from 'expo-router';
import React, { useEffect, useState } from 'react';
import { ActivityIndicator, View } from 'react-native';

export default function SplashScreen() {
  const backgroundColor = useThemeColor({}, 'background');
  const primaryColor = useThemeColor({}, 'primary');
  const [isLoading, setIsLoading] = useState(true);
  const { initializePushNotifications } = usePushNotifications();

  useEffect(() => {
    checkOnboardingStatus();
  }, []);

  const checkOnboardingStatus = async () => {
    try {
      // 先预加载用户数据，包括 onboarding 状态
      console.log('开始预加载用户数据（包含 onboarding 状态）...');
      const userData = await preloadUserData();
      console.log('用户数据预加载完成，onboarding 状态:', userData.onboardingCompleted);

      // 初始化推送通知（不阻塞应用启动，且不会请求权限）
      console.log('开始初始化推送通知基础服务...');
      initializePushNotifications().catch((error) => {
        console.warn('推送通知初始化失败，但不影响应用正常使用:', error);
      });

      // 根据预加载的状态决定跳转
      if (userData.onboardingCompleted) {
        console.log('用户已完成引导，跳转到统计页面');
        router.replace(ROUTES.TAB_STATISTICS);
      } else {
        console.log('用户未完成引导，跳转到引导页面');
        router.replace(ROUTES.ONBOARDING);
      }
    } catch (error) {
      console.error('检查引导状态或预加载用户数据失败:', error);
      // 如果出现错误，默认进入主应用（假设已完成引导）
      router.replace(ROUTES.TAB_STATISTICS);
    }
    setIsLoading(false);
  };

  if (!isLoading) {
    return null;
  }

  return (
    <ThemedView style={{
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor
    }}>
      <View style={{
        width: 80,
        height: 80,
        borderRadius: 40,
        // backgroundColor: primaryColor,
        justifyContent: 'center',
        alignItems: 'center',
        marginBottom: 20,
      }}>

      </View>
      <ActivityIndicator size="large" color={primaryColor} />
    </ThemedView>
  );
}
