import { View, StyleSheet, Alert } from 'react-native';
import { useRoute, RouteProp, useNavigation } from '@react-navigation/native';
import { useEffect, useState } from 'react';
import { payApi, PaymentInfoResponse } from '../../services/api/payApi';
import { WebView } from "react-native-webview";
import * as Linking from 'expo-linking';
import { navigate } from '../../navigation/RootNavigation';

type PayScreenRouteProp = RouteProp<{
  Pay: { payUrl: string };
}, 'Pay'>;

export const Pay = () => {
    const [loading, setLoading] = useState(true);
    const route = useRoute<PayScreenRouteProp>();
    const navigation = useNavigation();
    const {payUrl} = route.params;
    const [payInfo, setPayInfo] = useState<PaymentInfoResponse>();

    useEffect(() => {
        console.log(route.params);
        console.log(payUrl);
        
        // 设置处理深度链接的监听器
        const handleDeepLink = ({ url }: { url: string }) => {
          console.log('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 || {};
            navigate('PaymentSuccessScreen', params);
          }
        };

        // 添加深度链接事件监听器
        const subscription = Linking.addEventListener('url', handleDeepLink);

        return () => {
          // 清理订阅
          subscription.remove();
        };
    }, []);

    const handleNavigationStateChange = (navState: any) => {
        console.log(navState);
        
        // 检查URL是否包含支付成功的回调参数
        const { url } = navState;
        if (url && url.includes('payment_success=true')) {
          // 如果网页URL中包含成功参数，可以在这里处理
          Alert.alert('检测到支付成功！');
          // navigation.navigate('PaymentConfirmation');
        }
    }
  return <View style={{ flex: 1 }}>
    {payUrl ? (
      <WebView
        source={{ uri: payUrl }}
        style={styles.webview}
        onNavigationStateChange={handleNavigationStateChange}
        onLoadStart={() => setLoading(true)}
        onLoadEnd={() => setLoading(false)}
        javaScriptEnabled={true}
        domStorageEnabled={true}
        startInLoadingState={true}
        scalesPageToFit={true}
        originWhitelist={['*']}
        userAgent="Mozilla/5.0 (Linux; Android 10; Pixel 3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Mobile Safari/537.36"
        onShouldStartLoadWithRequest={(request) => {
          console.log('Load request:', request);
          
          // 检查URL是否是支付成功的深度链接
          const { url } = request;
          if (
            url && (
              url.startsWith('myapp://payment-success') ||
              url.startsWith('exp://192.168.0.101:8084/--/payment-success')
            )
          ) {
            // 解析参数
            const parsed = Linking.parse(url);
            const params = parsed.queryParams || {};
            // 跳转到支付成功页面
            navigate('PaymentSuccessScreen', params);
            return false; // 不在WebView中加载
          }
          
          // 允许所有其他请求
          return true;
        }}
      />
    ) : (
      <View>
        {/* Add fallback content here */}
      </View>
    )}
  </View>
}

const styles = StyleSheet.create({
  webview: {
    flex: 1,
  },
});
