import { Colors } from "@/constants/Colors";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useEffect } from "react";
import {
    ActivityIndicator,
    AppState,
    StyleSheet,
    Text,
    View,
} from "react-native";

/**
 * Alipay Callback Handler
 * Handles the "asios://safepay" deep link from Alipay.
 * Automatically goes back to invoke the native SDK's callback handling.
 */
export default function AlipayResult() {
  const router = useRouter();
  const params = useLocalSearchParams();

  useEffect(() => {
    console.log("Alipay callback params:", params);

    let hasNavigated = false;
    let fallbackTimer: ReturnType<typeof setTimeout>;

    const navigateBack = () => {
      if (hasNavigated) return;
      hasNavigated = true;
      if (router.canGoBack()) {
        router.back();
      } else {
        router.replace("/");
      }
    };

    // Listen for AppState changes to know when user actually returns to the app
    const subscription = AppState.addEventListener("change", (nextAppState) => {
      if (nextAppState === "active") {
        // App has returned to foreground. Give a tiny delay for React Native to settle.
        setTimeout(navigateBack, 500);
      }
    });

    // Fallback: if AppState doesn't trigger for some reason, navigate after a max delay (e.g., 2000ms)
    fallbackTimer = setTimeout(navigateBack, 2000);

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

  return (
    <View style={styles.container}>
      <ActivityIndicator size="large" color={Colors.neonBlue || "#00F3FF"} />
      <Text style={styles.text}>正在返回应用...</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: Colors.darkBg || "#121212",
  },
  text: {
    marginTop: 20,
    color: Colors.textSecondary || "#aaa",
    fontSize: 14,
  },
});
