import "react-native-gesture-handler";
import React from "react";
import { useEffect, useState } from "react";
import { userApi } from "./app/services/api/userApi";
import useUserStore from "./app/store/user";
import useBurialPointStore from "./app/store/burialPoint";
import { AuthProvider, useAuth } from "./app/contexts/AuthContext";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { AppNavigator } from "./app/navigation/AppNavigator";
import { View, ActivityIndicator, Alert } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import "./app/i18n";
import * as Linking from 'expo-linking';

// 定义全局事件处理支付成功
export const PAYMENT_SUCCESS_EVENT = 'PAYMENT_SUCCESS_EVENT';

function AppContent() {
  const { setUser } = useUserStore();
  const { login, logout } = useAuth();
  const { logAppLaunch } = useBurialPointStore();
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const initApp = async () => {
      try {
        const token = await AsyncStorage.getItem("token");
        if (token) {
          try {
            const user = await userApi.getProfile();        
            setUser(user);
            login();
          } catch (error) {
            console.error('Failed to get user profile:', error);
            logout();
          }
        }
        // 记录应用启动成功埋点
        logAppLaunch(true);
      } catch (error) {
        console.error('App initialization error:', error);
        // 记录应用启动失败埋点
        logAppLaunch(false);
      } finally {
        setIsLoading(false);
      }
    };

    initApp();
  }, []);

  // 添加深度链接处理
  useEffect(() => {
    // 处理深度链接
    const handleDeepLink = ({ url }: { url: string }) => {
      console.log('Global deep link received:', url);
      if (
        url.startsWith('myapp://payment-success') ||
        url.startsWith('exp://192.168.0.101:8084/--/payment-success')
      ) {
        // 解析参数
        const parsed = Linking.parse(url);
        const params = parsed.queryParams || {};
        const paymentId = params.paymentId || '';
        const token = params.token || '';
        const payerId = params.PayerID || '';
        
        Alert.alert(
          '支付成功！',
          `支付ID: ${paymentId}\nToken: ${token}\nPayerID: ${payerId}`
        );
        // 这里可以做页面跳转或业务处理
      }
    };

    // 注册深度链接监听器
    const subscription = Linking.addEventListener('url', handleDeepLink);

    // 处理应用冷启动的深度链接
    Linking.getInitialURL().then((url) => {
      if (url && url.startsWith('myapp://payment-success')) {
        handleDeepLink({ url });
      }
    });

    return () => subscription.remove();
  }, []);

  if (isLoading) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <ActivityIndicator size="large" color="#0066FF" />
      </View>
    );
  }

  return <AppNavigator />;
}

export default function App() {
  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <AuthProvider>
        <AppContent />
      </AuthProvider>
    </GestureHandlerRootView>
  );
}
