import 'react-native-gesture-handler';

import React, { createContext, useContext, useRef, useState, useEffect, useCallback } from 'react';
import { Platform, StyleSheet, View, Alert } from 'react-native';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { MMKV } from 'react-native-mmkv';
import { WebView } from 'react-native-webview';

import { GoogleSignin } from '@react-native-google-signin/google-signin';
import { appleAuth } from '@invertase/react-native-apple-authentication';
import DeviceInfo from 'react-native-device-info';
import { AUTH_CONFIG } from '@/config/auth';


import ApplicationNavigator from '@/navigation/Application';
import { ThemeProvider } from '@/theme';
import '@/translations';


import { eventTypeEnum } from './utils/h5';
import useSubscription from './hooks/useSub';


import { useRequest, setToken } from '@/hooks';


export const queryClient = new QueryClient({
  defaultOptions: {
    mutations: {
      retry: false,
    },
    queries: {
      retry: false,
    },
  },
});

export const storage = new MMKV();

// WebView预加载上下文
interface WebViewContextType {
  webViewRef: React.RefObject<WebView | null>;
  showWebView: boolean;
  setShowWebView: (show: boolean) => void;
}

const WebViewContext = createContext<WebViewContextType | null>(null);

export const useWebViewContext = () => {
  const context = useContext(WebViewContext);
  if (!context) {
    throw new Error('useWebViewContext must be used within WebViewProvider');
  }
  return context;
};

// 配置常量
// const DEFAULT_URL = 'http://localhost:5173';

const DEFAULT_URL = 'http://10.13.51.63:5173/';


// WebView用户代理
const USER_AGENT = Platform.select({
  ios: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1',
  android: 'Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36',
});

function App() {
  const webViewRef = useRef<WebView>(null);
  const [showWebView, setShowWebView] = useState(false);




  /**
   * 发送消息到 WebView
   */
  const sendMessageToWebView = (message: any) => {
    if (webViewRef.current) {
      const messageString = typeof message === 'string' ? message : JSON.stringify(message);
      // 使用更可靠的通信方式
      webViewRef.current.postMessage(messageString);
    }
  };

  /**
   * 处理来自 WebView 的消息
   */
  const handleWebViewMessage = (
    event: any,
  ) => {
    try {
      const messageData = event.nativeEvent.data;
      const { type, data } = messageData ? JSON.parse(messageData) : {};
      console.log('Received message:', type, data);
      
      // 检查是否为登录请求
      if (type === eventTypeEnum.login2Native) {
        // 延迟执行登录以确保 WebView 已完全显示
        handleLogin();
      } 
      // 检查是否为订阅请求
      else if (type === eventTypeEnum.SUBSCRIPTION_REQUEST) {
        console.log('📱 收到订阅请求:', data);
        
        // 从 H5 传来的数据中获取订阅类型
        const { productId, subscriptionType } = data || {};
        
        // 根据订阅类型选择产品ID
        let targetProductId = productId;
        if (!targetProductId && subscriptionType) {
          targetProductId = subscriptionType === 'yearly' 
            ? SUBSCRIPTION_PRODUCT_IDS.YEARLY 
            : SUBSCRIPTION_PRODUCT_IDS.MONTHLY;
        }
        
        handleInAppPurchase(targetProductId)
          .then(() => {
            console.log('✅ 订阅流程已启动');
          })
          .catch((error) => {
            console.error('❌ 启动订阅失败:', error);
            sendMessageToWebView({
              type: 'SUBSCRIPTION_ERROR',
              status: 'error',
              message: error.message || '订阅失败',
            });
          });
      }
      // 检查是否为恢复购买请求
      else if (type === eventTypeEnum.RESTORE_PURCHASE_REQUEST) {
        console.log('收到恢复购买请求');
        restorePurchases()
          .then(() => {
            console.log('恢复购买流程已完成');
          })
          .catch((error) => {
            console.error('恢复购买失败:', error);
            sendMessageToWebView({
              type: 'RESTORE_PURCHASE_ERROR',
              status: 'error',
              message: error.message || '恢复购买失败'
            });
          });
      }
    } catch (error) {
      console.error('处理 WebView 消息时出错:', error);
    }
  };

  const handleLogin = async () => {
    try {
      const deviceId = await DeviceInfo.getUniqueId();
      console.log('设备ID:', deviceId);


      if (Platform.OS === 'ios') {
        // iOS使用Apple登录
        await handleAppleLogin();
      } else {
        // Android使用Google登录
        await handleGoogleLogin();
      }
      
    } catch (error) {
      console.error('登录失败:', error);
      Alert.alert('登录失败', '请稍后重试');
    }
  };


  const handleAppleLogin = async () => {
    try {
      // 执行Apple登录请求
      const appleAuthRequestResponse = await appleAuth.performRequest({
        requestedOperation: appleAuth.Operation.LOGIN,
        requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
      });

      // 获取凭证状态
      const credentialState = await appleAuth.getCredentialStateForUser(
        appleAuthRequestResponse.user,
      );
      
      console.log('凭证状态:', credentialState, '(0=REVOKED, 1=AUTHORIZED, 2=NOT_FOUND)');

      // 如果performRequest成功返回，说明登录已完成
      // 模拟器中credentialState可能为0(REVOKED)，但不影响登录流程
      console.log('appleAuthRequestResponse.user',appleAuthRequestResponse.user)
      debugger
      if (appleAuthRequestResponse.user) {
        debugger
        console.log('Apple登录成功:', appleAuthRequestResponse);
        
        // 仅在真机且状态为REVOKED时警告
        if (credentialState === appleAuth.State.REVOKED && !__DEV__) {
          console.warn('⚠️ 凭证状态为REVOKED，但登录已完成');
        }
        sendMessageToWebView({
          type: eventTypeEnum.H5_LOGIN_SUCCESS_IOS,
          message: '登录成功',
          data: appleAuthRequestResponse
        })
      } else {
        console.log('未获取到用户信息');
        // throw new Error('未获取到用户信息');
      }
    } catch (error) {
      console.error('Apple登录失败:', error);
      // throw error;
    }
  };

  const handleGoogleLogin = async () => {
    try {
      // 检查是否有Google Play Services
      const hasPlayServices = await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: false });
      
      if (!hasPlayServices) {
        console.log('Google Play Services不可用，使用Mock数据');
        // Mock登录数据（仅用于开发测试）
        const mockUserInfo = {
          data: {
            user: {
              id: 'mock_user_123',
              name: '测试用户',
              email: 'test@example.com',
              photo: null,
            },
          },
        };
        Alert.alert('开发模式', '当前使用Mock登录数据（Google服务不可用）');
        sendMessageToWebView({
          type: eventTypeEnum.H5_LOGIN_SUCCESS_ANDROID,
          status: 'success',
          message: '登录成功（Mock模式）',
          data: mockUserInfo,
        });
        return;
      }

      // 配置Google登录
      await GoogleSignin.configure({
        webClientId: AUTH_CONFIG.GOOGLE.WEB_CLIENT_ID,
        offlineAccess: true,
      });
      
      // 执行登录
      const userInfo = await GoogleSignin.signIn();
      console.log('Google登录成功:', userInfo);
      Alert.alert('登录成功', `欢迎 ${userInfo.data?.user.name || '用户'}`);  
      sendMessageToWebView({
        type: 'LOGIN_SUCCESS_ANDROID',
        status: 'success',
        message: '登录成功',
        data: userInfo
      })
    } catch (error) {
      console.error('Google登录失败:', error);
      throw error;
    }
  };


  // 定义订阅产品ID（根据你的App Store/Google Play配置修改）
  const SUBSCRIPTION_PRODUCT_IDS = {
    MONTHLY: Platform.select({
      ios: 'com.recipemuse.premium.monthly',
      android: 'com.recipemuse.premium.monthly',
    }) || 'com.recipemuse.premium.monthly',
    YEARLY: Platform.select({
      ios: 'com.recipemuse.premium.yearly',
      android: 'com.recipemuse.premium.yearly',
    }) || 'com.recipemuse.premium.yearly',
  };

  // 使用订阅 hook
  const {
    connected,
    products,
    loading,
    error,
    purchasing,
    handlePurchase,
    restorePurchases,
    getProduct,
    clearError,
  } = useSubscription({
    productIds: [SUBSCRIPTION_PRODUCT_IDS.MONTHLY, SUBSCRIPTION_PRODUCT_IDS.YEARLY],
    productType: 'subs',
    sendMessageToWebView,
    onPurchaseComplete: (purchase) => {
      console.log('✅ 订阅购买成功:', purchase);
      // 可以在这里添加额外的成功处理逻辑
      // 例如：更新用户状态、记录分析事件等
    },
    onPurchaseFailed: (error) => {
      console.error('❌ 订阅购买失败:', error);
      // 可以在这里添加额外的失败处理逻辑
      // 例如：记录错误日志、发送错误报告等
    },
  });

  // 处理订阅请求
  const handleInAppPurchase = useCallback(async (productId?: string) => {
    try {
      // 如果没有传入 productId，默认使用月度订阅
      const targetProductId = productId || SUBSCRIPTION_PRODUCT_IDS.MONTHLY;
      
      console.log('🛒 开始订阅流程:', targetProductId);
      console.log('📦 可用产品:', products);
      console.log('🔌 IAP连接状态:', connected);

      // 检查连接状态
      if (!connected) {
        const errorMsg = '应用商店未连接，请稍后重试';
        Alert.alert('错误', errorMsg);
        sendMessageToWebView({
          type: 'SUBSCRIPTION_ERROR',
          status: 'error',
          message: errorMsg,
        });
        return;
      }

      // 检查产品是否已加载
      const product = getProduct(targetProductId);
      if (!product) {
        const errorMsg = '订阅产品不可用，请稍后重试';
        console.warn('⚠️ 产品未找到:', targetProductId);
        Alert.alert('错误', errorMsg);
        sendMessageToWebView({
          type: 'SUBSCRIPTION_ERROR',
          status: 'error',
          message: errorMsg,
        });
        return;
      }

      console.log('💰 产品信息:', product);
      
      // 发起购买
      await handlePurchase(targetProductId);
    } catch (error) {
      console.error('订阅流程错误:', error);
      const errorMessage = error instanceof Error ? error.message : '订阅失败';
      sendMessageToWebView({
        type: 'SUBSCRIPTION_ERROR',
        status: 'error',
        message: errorMessage,
      });
      throw error;
    }
  }, [connected, products, handlePurchase, getProduct, sendMessageToWebView, SUBSCRIPTION_PRODUCT_IDS]);
  

  return (
    <GestureHandlerRootView style={styles.container}>
      <QueryClientProvider client={queryClient}>
        <ThemeProvider storage={storage}>
          <WebViewContext.Provider value={{ webViewRef, showWebView, setShowWebView }}>
            <View style={styles.container}>
              <ApplicationNavigator />
              
              {/* 预加载的WebView，通过样式控制显示/隐藏 */}
              <View style={[
                styles.webViewContainer,
                showWebView ? styles.webViewVisible : styles.webViewHidden,
                __DEV__ && showWebView ? styles.webViewDebug : null // 开发模式下添加调试样式
              ]}>
                <WebView
                  ref={webViewRef}
                  source={{ uri: DEFAULT_URL }}
                  style={styles.webView}
                  userAgent={USER_AGENT}
                  javaScriptEnabled={true}
                  domStorageEnabled={true}
                  startInLoadingState={true}
                  scalesPageToFit={true}
                  allowsBackForwardNavigationGestures={Platform.OS === 'ios'}
                  onMessage={(event) => handleWebViewMessage(event)}
                  onError={(error) => console.error('WebView 错误:', error)}
                  onHttpError={(error) => console.error('WebView HTTP 错误:', error)}
                />
              </View>
            </View>
          </WebViewContext.Provider>
        </ThemeProvider>
      </QueryClientProvider>
    </GestureHandlerRootView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  webViewContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 1000,
  },
  webViewVisible: {
    opacity: 1,
  },
  webViewHidden: {
    opacity: 0,
    transform: [{ translateX: -9999 }], // 偏移到屏幕外
  },
  webView: {
    flex: 1,
  },
  // 添加一个新的样式用于调试模式
  webViewDebug: {
    top: 20,    // 留出顶部空间
    left: 10,   // 留出左侧空间
    right: 10,  // 留出右侧空间
    bottom: 20, // 留出底部空间
    borderRadius: 10, // 添加圆角以便识别
  },
});

export default App;
