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

    // In TestFlight/Release builds, performing a router.back() or router.dismiss() here
    // forces a React Navigation transition that often unmounts the underlying component
    // (CheckoutModal) BEFORE the native `Alipay.pay()` Promise has time to resolve and
    // trigger `handleSuccess`.

    // Instead of forcing a navigation here, we simply act as a passive sink for the deep link
    // to prevent the "Unmatched Route" warning. We trust the original `Alipay.pay()`
    // call in CheckoutModal to receive its native completion event and navigate the user
    // to the result screen (e.g., /happy-spin) which will naturally replace this route.

    // To ensure the user isn't stuck if the payment was cancelled or failed natively,
    // we provide a manual close button, or rely on them swiping back.
  }, []);

  return (
    <View style={styles.container}>
      <ActivityIndicator size="large" color={Colors.neonBlue || "#00F3FF"} />
      <Text style={styles.text}>正在确认支付结果...</Text>
      <Text
        style={styles.subtext}
        onPress={() => {
          if (router.canGoBack()) router.back();
          else router.replace("/");
        }}
      >
        如长时间未响应，请点击此处返回
      </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: 16,
    fontWeight: "bold",
  },
  subtext: {
    marginTop: 30,
    color: Colors.neonPink || "#FF007F",
    fontSize: 14,
    textDecorationLine: "underline",
    padding: 10,
  },
});
