import { Colors } from "@/constants/Colors";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useEffect } from "react";
import { ActivityIndicator, 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);

    // The native SDK (expo-native-alipay) listens for the app verify event
    // and resolves the Promise in the calling component (Recharge/Checkout).
    // This route mainly exists to prevent "Unmatched Route" errors.
    // We simply dismiss it to reveal the underlying screen.
    const timer = setTimeout(() => {
      // Use router.dismiss() if available in stack, or back()
      if (router.canGoBack()) {
        router.back();
      } else {
        // Fallback if launched directly (unlikely for payment callback)
        router.replace("/");
      }
    }, 500); // Short delay to allow smooth transition

    return () => clearTimeout(timer);
  }, []);

  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,
  },
});
