import React from 'react';
import { StyleSheet, View } from 'react-native';
import WebView from 'react-native-webview';
import type { WebViewNavigationEvent } from 'react-native-webview/src/WebViewTypes';

interface TamaraCheckoutURLProps {
  checkoutURL: string;
  successURL: string;
  failURL: string;
  cancelURL: string;
  onSuccess: () => void;
  onFail: () => void;
  onCancel: () => void;
}

const TamaraCheckoutURL: React.FC<TamaraCheckoutURLProps> = ({
  checkoutURL,
  successURL,
  failURL,
  cancelURL,
  onSuccess,
  onFail,
  onCancel,
}) => {
  const handleLoadStart = (syntheticEvent: WebViewNavigationEvent) => {
    // Change the event type
    const { nativeEvent } = syntheticEvent;
    if (nativeEvent.url && nativeEvent.url.includes(successURL)) {
      onSuccess();
    } else if (nativeEvent.url && nativeEvent.url.includes(failURL)) {
      onFail();
    } else if (nativeEvent.url && nativeEvent.url.includes(cancelURL)) {
      onCancel();
    }
  };

  const handleLoadError = () => {
    console.log('Webview load url fail');
  };

  return (
    <View style={styles.container}>
      <WebView
        originWhitelist={['*']}
        source={{ uri: checkoutURL }}
        onLoadStart={handleLoadStart}
        onError={handleLoadError}
        javaScriptEnabled
        domStorageEnabled
        allowsInlineMediaPlayback
        mediaCapturePermissionGrantType={'grant'}
        mediaPlaybackRequiresUserAction={false}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    minWidth: '100%',
    minHeight: 100,
    backgroundColor: 'gray',
  },
});

export default TamaraCheckoutURL;
