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, AUTH_EVENTS } 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";
import { EventEmitter } from 'events';

// 声明全局事件发射器类型
declare global {
  var EventEmitter: EventEmitter;
}

// 创建全局事件发射器
if (!global.EventEmitter) {
  global.EventEmitter = new EventEmitter();
}

// 定义全局事件处理支付成功
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);

  // 获取用户资料的函数
  const fetchUserProfile = async () => {
    try {
      const user = await userApi.getProfile();
      setUser(user);
      return true;
    } catch (error) {
      console.error('Failed to fetch user profile:', error);
      return false;
    }
  };

  useEffect(() => {
    const initApp = async () => {
      try {
        await fetchUserProfile();
        
        // 记录应用启动成功埋点
        logAppLaunch(true);
      } catch (error) {
        console.error('App initialization error:', error);
        // 记录应用启动失败埋点
        logAppLaunch(false);
      } finally {
        setIsLoading(false);
      }
    };

    initApp();
  }, []);

  // 监听登录成功事件，刷新用户资料
  useEffect(() => {
    const handleLoginSuccess = () => {
      fetchUserProfile();
    };

    // 注册事件监听器
    global.EventEmitter.on(AUTH_EVENTS.LOGIN_SUCCESS, handleLoginSuccess);

    // 清理函数
    return () => {
      global.EventEmitter.off(AUTH_EVENTS.LOGIN_SUCCESS, handleLoginSuccess);
    };
  }, []);

  // 添加深度链接处理
  useEffect(() => {
    // 处理深度链接
    const handleDeepLink = ({ url }: { url: string }) => {
      console.log(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) => {
      console.log(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>
  );
}
