import React, { useRef, useState } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import WebView from 'react-native-webview';
import CookieManager from '@react-native-cookies/cookies';
import { PhonePeBusinessBindResult, WalletType } from './types';
import { Locale, defaultLocale } from './locale';

interface Props {
    isDebug: boolean;
    processString: string;
    onSuccess: (result: PhonePeBusinessBindResult) => void;
    onError: (error: string) => void;
    locale?: Locale;
}

export const PhonePeBusinessBind: React.FC<Props> = ({ isDebug, processString, onSuccess, onError, locale = defaultLocale }) => {
    const webViewRef = useRef<WebView>(null);
    const [step, setStep] = useState<'login' | 'extracting' | 'checking'>('checking');
    const cookieRef = useRef<string>('');
    const xCsrfTokenRef = useRef<string>('');
    const fingerprintRef = useRef<string>('');
    const userATokenRef = useRef<string>('');
    const userRTokenRef = useRef<string>('');
    const hasExtractedRef = useRef<boolean>(false);

    const log = function (...args: any[]) {
        if (!isDebug) {
            return;
        }
        console.log(...args);
    };

    const error = function (...args: any[]) {
        if (!isDebug) {
            return;
        }
        console.error(...args);
    };

    const warn = function (...args: any[]) {
        if (!isDebug) {
            return;
        }
        console.warn(...args);
    };

    const consoleInterceptJS = `
    (function() {
      const IS_DEBUG = ${isDebug};
      const originalLog = console.log;
      const originalError = console.error;
      const originalWarn = console.warn;
      
      window.log = function(...args) {
        if (!IS_DEBUG) return;
        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) {}
      };
      
      window.error = function(...args) {
        if (!IS_DEBUG) return;
        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) {}
      };
      
      window.warn = function(...args) {
        if (!IS_DEBUG) return;
        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) {}
      };
    })();
    true;
  `;

    const injectedJS = `
    ${consoleInterceptJS}
    (function() {
      if (document.readyState !== 'complete') {
        window.addEventListener('load', extractData);
      } else {
        extractData();
      }
      
      function extractData() {
        try {
          const cookies = document.cookie;
          log('[PhonePeBind] Extracting cookies...');
          
          const userAToken = cookies.match(/MERCHANT_USER_A_TOKEN=([^;]+)/)?.[1];
          const userRToken = cookies.match(/MERCHANT_USER_R_TOKEN=([^;]+)/)?.[1];
          const ckbToken = cookies.match(/_CKB2N1BHVZ=([^;]+)/)?.[1];
          const csrfToken = cookies.match(/_X52F70K3N=([^;]+)/)?.[1];
          const fingerprintValue = cookies.match(/_F1P21N7=([^;]+)/)?.[1];
          
          log('[PhonePeBind] MERCHANT_USER_A_TOKEN:', userAToken ? 'found' : 'not found');
          log('[PhonePeBind] MERCHANT_USER_R_TOKEN:', userRToken ? 'found' : 'not found');
          log('[PhonePeBind] _X52F70K3N:', csrfToken ? 'found' : 'not found');
          log('[PhonePeBind] _F1P21N7:', fingerprintValue ? 'found' : 'not found');
          
          if (userAToken && userRToken && csrfToken && fingerprintValue) {
            const cookieStr = 'MERCHANT_USER_A_TOKEN=' + userAToken + ';MERCHANT_USER_R_TOKEN=' + userRToken + ';_CKB2N1BHVZ=' + ckbToken + ';';
            const fingerprint = fingerprintValue + '.' + fingerprintValue + '.' + fingerprintValue + '.' + fingerprintValue;
            
            log('[PhonePeBind] All cookies found, posting message');
            window.ReactNativeWebView.postMessage(JSON.stringify({
              type: 'phonepe_business',
              success: true,
              cookie: cookieStr,
              xCsrfToken: csrfToken,
              fingerprint: fingerprint,
              userAToken: userAToken,
              userRToken: userRToken
            }));
          } else {
            log('[PhonePeBind] Not all cookies found, need login');
            window.ReactNativeWebView.postMessage(JSON.stringify({
              type: 'need_login'
            }));
          }
        } catch (e) {
          error('[PhonePeBind] Extract error:', e.toString());
          window.ReactNativeWebView.postMessage(JSON.stringify({
            type: 'error',
            message: e.toString()
          }));
        }
      }
    })();
    true;
  `;

    const fetchInfo = async (cookie: string, csrfToken: string, fingerprint: string) => {
        log('[PhonePeBind] Fetching user info...');
        try {
            const response = await fetch('https://web-api.phonepe.com/apis/mi-web/v1/user/me', {
                headers: {
                    'Cookie': cookie,
                    'X-APP-ID': 'oculus',
                    'X-SOURCE-TYPE': 'WEB',
                    'X-SOURCE-PLATFORM': 'WEB',
                    'NAMESPACE': 'insights',
                    'FINGERPRINT': fingerprint,
                    'Accept': 'application/json, text/plain, */*',
                    'Origin': 'https://business.phonepe.com',
                    'Referer': 'https://business.phonepe.com/'
                }
            });
            const info = await response.json();
            log('[PhonePeBind] User info received, status:', response.status, 'length:', info.length);
            
            if (!response.ok || response.status !== 200) {
                warn('[PhonePeBind] User info API returned non-200 status:', response.status);
                return null;
            }
            
            return info;
        } catch (e) {
            error('[PhonePeBind] Fetch user info error:', e);
            return null;
        }
    };

    const fetchQRData = async (cookie: string, csrfToken: string, fingerprint: string) => {
        log('[PhonePeBind] Fetching QR data from RN...');
        try {
            // 获取用户信息
            const userInfo = await fetchInfo(cookie, csrfToken, fingerprint);
            
            // 获取 QR 列表
            const response = await fetch('https://web-api.phonepe.com/apis/mi-web/v1/qrpos/list?mappedObjectType=QR_CODE&start=0&limit=100', {
                headers: {
                    'Cookie': cookie,
                    'X-CSRF-TOKEN': csrfToken,
                    'X-Fingerprint': fingerprint
                }
            });
            const qrData = await response.text();
            log('[PhonePeBind] QR data received, status:', response.status, 'length:', qrData.length);

            if (!response.ok || response.status !== 200) {
                log('[PhonePeBind] QR API returned non-200 status:', response.status);
                hasExtractedRef.current = false;
                setStep('login');
                return;
            }

            log('[PhonePeBind] ✅ QR data received, length:', qrData.length);
            if (userInfo) {
                log('[PhonePeBind] ✅ User info received, length:', userInfo.length);
            }

            onSuccess({
                type: WalletType.PHONEPE_BUSINESS,
                success: true,
                cookie: cookieRef.current,
                xCsrfToken: xCsrfTokenRef.current,
                fingerprint: fingerprintRef.current,
                userAToken: userATokenRef.current,
                userRToken: userRTokenRef.current,
                userInfo: userInfo || undefined,
                qrData: JSON.parse(qrData) || []
            } as PhonePeBusinessBindResult);
        } catch (e) {
            error('[PhonePeBind] Fetch error:', e);
            hasExtractedRef.current = false;
            setStep('login');
            onError(e instanceof Error ? e.message : String(e));
        }
    };

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

            // 转发 WebView console 输出
            if (data.type === 'console') {
                const prefix = '[WebView]';
                if (data.level === 'error') {
                    error(prefix, data.message);
                } else if (data.level === 'warn') {
                    warn(prefix, data.message);
                } else {
                    log(prefix, data.message);
                }
                return;
            }

            log('[PhonePeBind] Received message type:', data.type);

            if (data.type === 'error') {
                error('[PhonePeBind] Error:', data.message);
                onError(data.message);
                return;
            }

            if (data.type === 'need_login') {
                // 如果已经在 extracting 状态，忽略 need_login 消息
                if (step === 'extracting') {
                    log('[PhonePeBind] Already extracting, ignore need_login');
                    return;
                }
                log('[PhonePeBind] Need login, showing login page');
                hasExtractedRef.current = false;
                setStep('login');
                return;
            }

            if (data.type === 'phonepe_business' && data.success && !hasExtractedRef.current && step !== 'extracting') {
                // 立即设置标志位和状态，防止重复触发
                hasExtractedRef.current = true;
                setStep('extracting');

                cookieRef.current = data.cookie;
                xCsrfTokenRef.current = data.xCsrfToken;
                fingerprintRef.current = data.fingerprint;
                userATokenRef.current = data.userAToken;
                userRTokenRef.current = data.userRToken;

                log('[PhonePeBind] ✅ Cookie extracted:', data.cookie.substring(0, 30) + '...');
                log('[PhonePeBind] ✅ CSRF Token extracted:', data.xCsrfToken.substring(0, 30) + '...');
                log('[PhonePeBind] ✅ Fingerprint extracted:', data.fingerprint.substring(0, 30) + '...');
                log('[PhonePeBind] ✅ UserA Token:', data.userAToken.substring(0, 30) + '...');
                log('[PhonePeBind] ✅ UserR Token:', data.userRToken.substring(0, 30) + '...');

                fetchQRData(data.cookie, data.xCsrfToken, data.fingerprint);
            }

        } catch (e) {
            error('[PhonePeBind] Parse error:', e);
            onError(e instanceof Error ? e.message : String(e));
        }
    };

    const handleNavigationStateChange = async (navState: any) => {
        const url = navState.url;
        log('[PhonePeBind] Navigation state changed:', url, 'loading:', navState.loading);

        const isLoggedIn = url.includes('business.phonepe.com') && !url.includes('/login');

        // 如果已经在 extracting 状态，不再处理
        if (navState.loading === false && !hasExtractedRef.current && step !== 'extracting') {
            if (step === 'checking') {
                setStep('login');
            }

            if (isLoggedIn) {
                log('[PhonePeBind] Detected logged in page, auto extracting...');

                try {
                    const cookies = await CookieManager.get('https://business.phonepe.com');

                    const userAToken = cookies.MERCHANT_USER_A_TOKEN?.value;
                    const userRToken = cookies.MERCHANT_USER_R_TOKEN?.value;
                    const ckbToken = cookies._CKB2N1BHVZ?.value;
                    const csrfToken = cookies._X52F70K3N?.value;
                    const fingerprintValue = cookies._F1P21N7?.value;

                    log('[PhonePeBind] MERCHANT_USER_A_TOKEN from native:', userAToken ? 'found' : 'not found');
                    log('[PhonePeBind] MERCHANT_USER_R_TOKEN from native:', userRToken ? 'found' : 'not found');
                    log('[PhonePeBind] _X52F70K3N from native:', csrfToken ? 'found' : 'not found');
                    log('[PhonePeBind] _F1P21N7 from native:', fingerprintValue ? 'found' : 'not found');

                    if (userAToken && userRToken && csrfToken && fingerprintValue) {
                        // 立即设置标志位，防止重复触发
                        hasExtractedRef.current = true;
                        setStep('extracting');

                        const cookieStr = `MERCHANT_USER_A_TOKEN=${userAToken};MERCHANT_USER_R_TOKEN=${userRToken};_CKB2N1BHVZ=${ckbToken};`;
                        const fingerprint = `${fingerprintValue}.${fingerprintValue}.${fingerprintValue}.${fingerprintValue}`;

                        cookieRef.current = cookieStr;
                        xCsrfTokenRef.current = csrfToken;
                        fingerprintRef.current = fingerprint;
                        userATokenRef.current = userAToken;
                        userRTokenRef.current = userRToken;

                        log('[PhonePeBind] ✅ Cookie extracted from native:', cookieStr.substring(0, 30) + '...');
                        log('[PhonePeBind] ✅ CSRF Token extracted from native:', csrfToken.substring(0, 30) + '...');
                        log('[PhonePeBind] ✅ UserA Token:', userAToken.substring(0, 30) + '...');
                        log('[PhonePeBind] ✅ UserR Token:', userRToken.substring(0, 30) + '...');

                        fetchQRData(cookieStr, csrfToken, fingerprint);
                    } else {
                        log('[PhonePeBind] Not all cookies found, waiting for login');
                    }
                } catch (err) {
                    error('[PhonePeBind] CookieManager error:', err);
                }
            }
        }
    };

    return (
        <View style={styles.container}>
            <WebView
                ref={webViewRef}
                source={{ uri: 'https://business.phonepe.com/dashboard' }}
                injectedJavaScript={injectedJS}
                onMessage={handleMessage}
                onNavigationStateChange={handleNavigationStateChange}
                javaScriptEnabled={true}
                domStorageEnabled={true}
                thirdPartyCookiesEnabled={true}
                sharedCookiesEnabled={true}
                onLoadEnd={() => {
                    log('[PhonePeBind] WebView loaded, step:', step);
                }}
            />
            {step === 'extracting' && (
                <View style={styles.overlay}>
                    <Text style={styles.overlayText}>{processString || locale.phonePeBusiness.processing}</Text>
                </View>
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    overlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0,0,0,0.7)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    overlayText: {
        color: 'white',
        fontSize: 16,
    },
});
