import { View, StyleSheet } from 'react-native';
import { useRoute, RouteProp } from '@react-navigation/native';
import { useEffect, useState } from 'react';
import { payApi, PaymentInfoResponse } from '../../services/api/payApi';
import { WebView } from "react-native-webview";

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

export const Pay = () => {
    const [loading, setLoading] = useState(true);
    const route = useRoute<PayScreenRouteProp>();
    const {order_id} = route.params;
    const [payInfo, setPayInfo] = useState<PaymentInfoResponse>();
    const getPayInfo = async () => {
        const data = {
            order_id: order_id,
            method: 'paypal',
            amount: '100',
            currency: 'USD'
        }
        const res = await payApi.getPayInfo(data);
        console.log('res',res);
        
        setPayInfo(res);
    }
    useEffect(() => {
        
        getPayInfo();
    },[])
    const handleNavigationStateChange = (navState: any) => {
        console.log(navState);
    }
  return <View style={{ flex: 1 }}>
    {payInfo?.payment_url ? (
      <WebView
        source={{ uri: payInfo.payment_url }}
        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(request);
          
          // 允许所有请求
          return true;
        }}
      />
    ) : (
      <View>
        {/* Add fallback content here */}
      </View>
    )}
  </View>
}

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