import React, { useRef } from 'react';
import { View, StyleSheet } from 'react-native';
import WebView from 'react-native-webview';
import { BharatPeBusinessBindResult, WalletType } from './types';

interface Props {
    onSuccess: (result: BharatPeBusinessBindResult) => void;
    onError: (error: string) => void;
    isDebug?: boolean;
}

export const BharatPeBusinessBind: React.FC<Props> = ({ onSuccess, onError, isDebug = false }) => {
    const webViewRef = useRef<WebView>(null);

    const log = (...args: any[]) => {
        if (!isDebug) return;
        console.log('[BharatPe]', ...args);
    };

    const isSuccess = useRef<boolean>(false);
    const onSuccessReal = (result: BharatPeBusinessBindResult) => {
        if (isSuccess.current) return;
        isSuccess.current = true; // 防止重复调用
        onSuccess(result);
    }

    const injectedJS = `
    (function() {
      // 防止重复执行
      if (window.__bharatpe_extracted) {
        console.log('Already extracted, skipping...');
        return;
      }
      
      // 修复 speechSynthesis API（关键！）
      if (!window.speechSynthesis) {
        window.speechSynthesis = {
          speak: function() {},
          cancel: function() {},
          pause: function() {},
          resume: function() {},
          getVoices: function() { return []; }
        };
      }
      
      // 拦截 console
      const originalLog = console.log;
      const originalError = console.error;
      const originalWarn = console.warn;
      
      console.log = function(...args) {
        originalLog.apply(console, args);
        try {
          window.ReactNativeWebView.postMessage(JSON.stringify({
            type: 'console',
            level: 'log',
            message: args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')
          }));
        } catch(e) {}
      };
      
      console.error = function(...args) {
        originalError.apply(console, args);
        try {
          window.ReactNativeWebView.postMessage(JSON.stringify({
            type: 'console',
            level: 'error',
            message: args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')
          }));
        } catch(e) {}
      };
      
      console.warn = function(...args) {
        originalWarn.apply(console, args);
        try {
          window.ReactNativeWebView.postMessage(JSON.stringify({
            type: 'console',
            level: 'warn',
            message: args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')
          }));
        } catch(e) {}
      };
      
      console.log('Console interceptor installed, speechSynthesis fixed');
      
      if (document.readyState !== 'complete') {
        console.log('Waiting for page load...');
        window.addEventListener('load', extractData);
      } else {
        console.log('Page already loaded, extracting in 2s...');
        setTimeout(extractData, 2000);
      }
      
      async function extractData() {
        console.log('Extracting USER_INFO from localStorage...');
        try {
          const userInfoStr = localStorage.getItem('USER_INFO');
          console.log('USER_INFO:', userInfoStr);
          
          if (!userInfoStr) {
            console.log('USER_INFO not found, user might not be logged in');
            return;
          }
          
          const userInfo = JSON.parse(userInfoStr);
          const cookie = document.cookie;
          
          console.log('Parsed userInfo:', JSON.stringify(userInfo));
          console.log('Cookie:', cookie);
          
          const accessToken = userInfo.accessToken || '';
          const merchantId = userInfo.merchant_id || '';
          
          // 获取 QR URL
          let qrUrl = '';
          if (accessToken && merchantId) {
            try {
              console.log('Fetching QR URL...');
              const qrResponse = await fetch('https://payments-tesseract.bharatpe.in/api/merchant/v1/downloadQr?merchantId=' + merchantId, {
                method: 'GET',
                headers: {
                  'token': accessToken,
                  'Accept': 'application/json'
                }
              });
              const qrData = await qrResponse.json();
              console.log('QR response:', JSON.stringify(qrData));
              if (qrData.status && qrData.data && qrData.data.url) {
                qrUrl = qrData.data.url;
                console.log('QR URL:', qrUrl);
              }
            } catch (e) {
              console.error('Fetch QR error:', e);
            }
          }
          
          window.ReactNativeWebView.postMessage(JSON.stringify({
            type: 'bharatpe_business',
            success: true,
            cookie: cookie,
            accessToken: accessToken,
            merchantId: merchantId,
            userName: userInfo.userName || '',
            email: userInfo.email || '',
            mobile: userInfo.mobile || '',
            qrUrl: qrUrl
          }));
          
          window.__bharatpe_extracted = true;
          console.log('Data sent to React Native');
        } catch (e) {
          console.error('Extract error:', e);
          window.ReactNativeWebView.postMessage(JSON.stringify({
            type: 'error',
            message: e.toString()
          }));
        }
      }
    })();
    true;
  `;

    const handleMessage = (event: any) => {
        try {
            const data = JSON.parse(event.nativeEvent.data);

            if (data.type === 'console') {
                const prefix = data.level === 'error' ? '❌' : data.level === 'warn' ? '⚠️' : '📝';
                log(`${prefix} [WebView Console]`, data.message);
                return;
            }

            if (data.type === 'error') {
                log('Error from WebView:', data.message);
                onError(data.message);
                return;
            }

            if (data.type === 'bharatpe_business' && data.success) {
                log('Success! Data received:', data);
                onSuccessReal(data as BharatPeBusinessBindResult);
            }
        } catch (e) {
            log('handleMessage error:', e);
            onError(e instanceof Error ? e.message : String(e));
        }
    };

    return (
        <View style={styles.container}>
            <WebView
                ref={webViewRef}
                source={{ uri: 'https://enterprise.bharatpe.in/' }}
                injectedJavaScript={injectedJS}
                injectedJavaScriptBeforeContentLoaded={`
                    if (!window.speechSynthesis) {
                        window.speechSynthesis = {
                        speak: function() {},
                        cancel: function() {},
                        pause: function() {},
                        resume: function() {},
                        getVoices: function() { return []; }
                        };
                    }
                    true;
                `}
                onMessage={handleMessage}
                onLoadStart={() => {
                    log('Page loading started');
                }}
                onLoadEnd={() => {
                    log('Page loaded, injecting JS');
                    webViewRef.current?.injectJavaScript(injectedJS);
                }}
                onNavigationStateChange={(navState) => {
                    log('Navigation changed:', navState.url);
                }}
                onError={(syntheticEvent) => {
                    const { nativeEvent } = syntheticEvent;
                    log('WebView error:', nativeEvent);
                }}
                onHttpError={(syntheticEvent) => {
                    const { nativeEvent } = syntheticEvent;
                    log('HTTP error:', nativeEvent.statusCode, nativeEvent.url);
                }}
                javaScriptEnabled={true}
                domStorageEnabled={true}
                thirdPartyCookiesEnabled={true}
                sharedCookiesEnabled={true}
                javaScriptCanOpenWindowsAutomatically={true}
                setSupportMultipleWindows={false}
                allowsInlineMediaPlayback={true}
                mediaPlaybackRequiresUserAction={false}
                originWhitelist={['*']}
                mixedContentMode="always"
                cacheEnabled={true}
                incognito={false}
                startInLoadingState={true}
                scalesPageToFit={true}
                allowsBackForwardNavigationGestures={true}
                allowsLinkPreview={false}
            />
        </View>
    );
};

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