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

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

export const PaytmBusinessBind: React.FC<Props> = ({ isDebug, processString, onSuccess, onError, locale = defaultLocale }) => {
    const webViewRef = useRef<WebView>(null);
    const [step, setStep] = useState<'login' | 'extracting' | 'checking' | 'completed'>('checking');
    const cookieRef = useRef<string>('');
    const xsrfTokenRef = 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);
    };

    // 拦截 console 输出
    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;
  `;

    // 检查 cookie 的 JS
    const checkCookieJS = `
    ${consoleInterceptJS}
    (function() {
      try {
        const cookies = document.cookie;
        log('[PaytmBind] All cookies:', cookies);
        
        // 列出所有 cookie 名称
        const cookieNames = cookies.split(';').map(c => c.trim().split('=')[0]);
        log('[PaytmBind] Cookie names:', cookieNames.join(', '));
        
        const sessionMatch = cookies.match(/SESSION=([^;]+)/);
        const xsrfMatch = cookies.match(/XSRF-TOKEN=([^;]+)/);
        
        log('[PaytmBind] SESSION match:', sessionMatch ? 'found' : 'not found');
        log('[PaytmBind] XSRF-TOKEN match:', xsrfMatch ? 'found' : 'not found');
        
        if (sessionMatch && xsrfMatch) {
          log('[PaytmBind] Found cookies, extracting...');
          window.ReactNativeWebView.postMessage(JSON.stringify({
            type: 'paytm_business',
            success: true,
            cookie: sessionMatch[1],
            xCsrfToken: xsrfMatch[1]
          }));
        } else {
          log('[PaytmBind] SESSION or XSRF-TOKEN not found, user needs to login');
          window.ReactNativeWebView.postMessage(JSON.stringify({
            type: 'need_login'
          }));
        }
      } catch (e) {
        error('[PaytmBind] Error:', e.toString());
        window.ReactNativeWebView.postMessage(JSON.stringify({
          type: 'error',
          message: e.toString()
        }));
      }
    })();
    true;
  `;

    const injectedJS = `
    ${consoleInterceptJS}
    (function() {
      // 等待页面加载完成
      if (document.readyState !== 'complete') {
        window.addEventListener('load', extractData);
      } else {
        extractData();
      }
      
      function extractData() {
        try {
          const cookies = document.cookie;
          log('[PaytmBind] Page loaded, extracting cookies...');
          
          // 列出所有 cookie 名称
          const cookieNames = cookies.split(';').map(c => c.trim().split('=')[0]);
          log('[PaytmBind] Available cookie names:', cookieNames.join(', '));
          
          const sessionMatch = cookies.match(/SESSION=([^;]+)/);
          const xsrfMatch = cookies.match(/XSRF-TOKEN=([^;]+)/);
          
          log('[PaytmBind] SESSION:', sessionMatch ? 'found' : 'not found');
          log('[PaytmBind] XSRF-TOKEN:', xsrfMatch ? 'found' : 'not found');
          
          if (sessionMatch && xsrfMatch) {
            log('[PaytmBind] Cookies found, will extract data');
            window.ReactNativeWebView.postMessage(JSON.stringify({
              type: 'paytm_business',
              success: true,
              cookie: sessionMatch[1],
              xCsrfToken: xsrfMatch[1]
            }));
          }
        } catch (e) {
          error('[PaytmBind] Extract error:', e.toString());
          window.ReactNativeWebView.postMessage(JSON.stringify({
            type: 'error',
            message: e.toString()
          }));
        }
      }
    })();
    true;
  `;

    const fetchQRData = async (cookie: string, xsrfToken: string) => {
        log('[PaytmBind] Fetching QR data with cookie:', cookie.substring(0, 20) + '...');
        log('[PaytmBind] XSRF Token:', xsrfToken.substring(0, 20) + '...');

        // 获取 context
        const contextJS = `
      (async function() {
        try {
          log('[PaytmBind] Fetching context...');
          const response = await fetch('https://dashboard.paytm.com/api/v1/context', {
            headers: {
              'Cookie': 'SESSION=${cookie}',
              'X-CSRF-TOKEN': '${xsrfToken}'
            }
          });
          const context = await response.text();
          log('[PaytmBind] Context received, status:', response.status, 'length:', context.length);
          
          // 检查 HTTP 状态码，非 200 都需要重新登录
          if (!response.ok || response.status !== 200) {
            log('[PaytmBind] Context API returned non-200 status:', response.status, 'user needs to login');
            window.ReactNativeWebView.postMessage(JSON.stringify({
              type: 'need_login'
            }));
            return;
          }
          
          // 检查返回内容是否包含错误
          try {
            const contextJson = JSON.parse(context);
            if (contextJson.error || contextJson.status >= 400) {
              log('[PaytmBind] Context contains error, user needs to login');
              window.ReactNativeWebView.postMessage(JSON.stringify({
                type: 'need_login'
              }));
              return;
            }
          } catch(e) {
            // 如果不是有效 JSON，也认为失败
            log('[PaytmBind] Context is not valid JSON, user needs to login');
            window.ReactNativeWebView.postMessage(JSON.stringify({
              type: 'need_login'
            }));
            return;
          }
          
          // 获取 QR 列表
          log('[PaytmBind] Fetching QR list...');
          const qrResponse = await fetch('https://dashboard.paytm.com/api/v4/qrcode/fetch/?pageNo=1&pageSize=100', {
            headers: {
              'Cookie': 'SESSION=${cookie}',
              'X-CSRF-TOKEN': '${xsrfToken}'
            }
          });
          const qrData = await qrResponse.text();
          log('[PaytmBind] QR data received, status:', qrResponse.status, 'length:', qrData.length);
          
          // 检查 QR API 状态码
          if (!qrResponse.ok || qrResponse.status !== 200) {
            log('[PaytmBind] QR API returned non-200 status:', qrResponse.status, 'user needs to login');
            window.ReactNativeWebView.postMessage(JSON.stringify({
              type: 'need_login'
            }));
            return;
          }
          
          // 检查 QR 数据是否包含错误
          try {
            const qrJson = JSON.parse(qrData);
            if (qrJson.error || qrJson.status >= 400) {
              log('[PaytmBind] QR data contains error, user needs to login');
              window.ReactNativeWebView.postMessage(JSON.stringify({
                type: 'need_login'
              }));
              return;
            }
          } catch(e) {
            // 如果不是有效 JSON，也认为失败
            log('[PaytmBind] QR data is not valid JSON, user needs to login');
            window.ReactNativeWebView.postMessage(JSON.stringify({
              type: 'need_login'
            }));
            return;
          }
          
          window.ReactNativeWebView.postMessage(JSON.stringify({
            type: 'paytm_qr_data',
            contextData: context,
            qrData: qrData
          }));
        } catch (e) {
          error('[PaytmBind] Fetch error:', e);
          // 任何异常都提示需要登录
          window.ReactNativeWebView.postMessage(JSON.stringify({
            type: 'need_login'
          }));
        }
      })();
      true;
    `;

        webViewRef.current?.injectJavaScript(contextJS);
    };

    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('[PaytmBind] Received message type:', data.type);

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

            if (data.type === 'need_login') {
                log('[PaytmBind] Need login, showing login page');
                hasExtractedRef.current = false; // 重置状态，允许重新提取
                setStep('login');
                return;
            }

            if (data.type === 'paytm_business' && data.success && !hasExtractedRef.current) {
                hasExtractedRef.current = true;
                cookieRef.current = data.cookie; // 只保存 SESSION 的值
                xsrfTokenRef.current = data.xCsrfToken;

                log('[PaytmBind] ✅ Cookie extracted:', data.cookie.substring(0, 30) + '...');
                log('[PaytmBind] ✅ XSRF Token extracted:', data.xCsrfToken.substring(0, 30) + '...');

                setStep('extracting');
                fetchQRData(data.cookie, data.xCsrfToken);
            }

            if (data.type === 'paytm_qr_data') {
                let qrList = [];
                try {
                    let qrJson = JSON.parse(data.qrData);
                    qrList = qrJson.response || [];
                } catch (e) {
                    error('[PaytmBind] Parse QR data error:', e);
                    onError(e instanceof Error ? e.message : String(e));
                    return;
                }
                const result: PaytmBusinessBindResult = {
                    type: WalletType.PAYTM_BUSINESS,
                    success: true,
                    cookie: cookieRef.current, // 只有 SESSION 的值
                    xCsrfToken: xsrfTokenRef.current,
                    contextData: data.contextData,
                    qrData: qrList,
                };

                log('[PaytmBind] ✅ All data extracted:');
                log('[PaytmBind] Cookie (SESSION value):', result.cookie.substring(0, 30) + '...');
                log('[PaytmBind] XSRF Token:', result.xCsrfToken.substring(0, 30) + '...');
                log('[PaytmBind] Context length:', data.contextData?.length || 0);
                log('[PaytmBind] QR data length:', data.qrData?.length || 0);

                onSuccess(result);
                setStep('completed');
            }
        } catch (e) {
            error('[PaytmBind] Parse error:', e);
            onError(e instanceof Error ? e.message : String(e));
        }
    };

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

        // 检测是否在登录后的页面（dashboard）
        const isLoggedIn = url.includes('dashboard.paytm.com') && !url.includes('/login');

        // 页面加载完成后检查 cookie
        if (navState.loading === false && !hasExtractedRef.current) {

            // 如果在 checking 状态，切换到 login
            if (step === 'checking') {
                setStep('login');
            }

            // 如果已经登录，自动触发提取
            if (isLoggedIn) {
                log('[PaytmBind] Detected logged in page, auto extracting...');

                // 使用 CookieManager 获取 HttpOnly cookie
                try {
                    const cookies = await CookieManager.get('https://dashboard.paytm.com');
                    // log('[PaytmBind] Cookies from CookieManager:', JSON.stringify(cookies, null, 2));

                    const sessionCookie = cookies.SESSION?.value;
                    const xsrfToken = cookies['XSRF-TOKEN']?.value;

                    log('[PaytmBind] SESSION from native:', sessionCookie ? 'found' : 'not found');
                    log('[PaytmBind] XSRF-TOKEN from native:', xsrfToken ? 'found' : 'not found');

                    if (sessionCookie && xsrfToken) {
                        hasExtractedRef.current = true;
                        cookieRef.current = sessionCookie;
                        xsrfTokenRef.current = xsrfToken;

                        log('[PaytmBind] ✅ Cookie extracted from native:', sessionCookie.substring(0, 30) + '...');
                        log('[PaytmBind] ✅ XSRF Token extracted from native:', xsrfToken.substring(0, 30) + '...');

                        setStep('extracting');
                        fetchQRData(sessionCookie, xsrfToken);
                    } else {
                        log('[PaytmBind] SESSION or XSRF-TOKEN not found, waiting for login');
                    }
                } catch (err) {
                    error('[PaytmBind] CookieManager error:', err);
                }
            }
        }
    };

    return (
        <View style={styles.container}>
            <WebView
                ref={webViewRef}
                source={{ uri: 'https://dashboard.paytm.com' }}
                injectedJavaScript={injectedJS}
                onMessage={handleMessage}
                onNavigationStateChange={handleNavigationStateChange}
                javaScriptEnabled={true}
                domStorageEnabled={true}
                thirdPartyCookiesEnabled={true}
                sharedCookiesEnabled={true}
                onLoadEnd={() => {
                    log('[PaytmBind] WebView loaded, step:', step);
                }}
            />
            {step === 'extracting' && (
                <View style={styles.overlay}>
                    <Text style={styles.overlayText}>{processString || locale.paytmBusiness.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,
    },
});
