// useSubscription.ts
import { useEffect, useRef, useState, useCallback } from 'react';
import { Platform, Alert } from 'react-native';
import { useIAP, ErrorCode, Product, Purchase, PurchaseError, ProductType, getAvailablePurchases as getAvailablePurchasesAPI } from 'react-native-iap';

interface UseSubscriptionParams {
  productIds?: string[];
  productType?: ProductType;
  sendMessageToWebView?: (msg: any) => void;
  onPurchaseComplete?: (purchase: Purchase) => void;
  onPurchaseFailed?: (error: PurchaseError) => void;
}

export interface SubscriptionState {
  connected: boolean;
  products: Product[];
  loading: boolean;
  error: string | null;
  purchasing: boolean;
}

// NOTE 文档：https://hyochan.github.io/react-native-iap/docs/intro

export default function useSubscription({
  productIds = ['com.example.coins.pack1', 'com.example.premium'],
  productType = 'subs',
  sendMessageToWebView,
  onPurchaseComplete,
  onPurchaseFailed,
}: UseSubscriptionParams = {}) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [purchasing, setPurchasing] = useState(false);
  const isProcessingRef = useRef(false);

  const {
    connected,
    products,
    fetchProducts,
    requestPurchase,
    finishTransaction,
  } = useIAP({
    onPurchaseSuccess: async (purchase) => {
      // 防止重复处理
      if (isProcessingRef.current) {
        console.log('Already processing a purchase, skipping...');
        return;
      }

      isProcessingRef.current = true;
      setPurchasing(true);

      try {
        console.log('Purchase successful:', purchase.productId);

        // 发送消息到 WebView
        sendMessageToWebView?.({
          type: 'PURCHASE_SUCCESS',
          data: {
            productId: purchase.productId,
            transactionId: 'transactionId' in purchase ? purchase.transactionId : purchase.id,
            purchaseToken: purchase.purchaseToken,
          },
        });

        // TODO: Verify the receipt on your backend before granting access
        // const isValid = await verifyReceiptOnBackend(purchase);
        // if (!isValid) {
        //   throw new Error('Invalid receipt');
        // }

        // 完成交易
        await finishTransaction({
          purchase,
          isConsumable: productType === 'in-app', // 订阅为 false，消耗品为 true
        });

        // 调用成功回调
        onPurchaseComplete?.(purchase);

        setError(null);
        Alert.alert('购买成功', '感谢您的购买！');
      } catch (error) {
        console.error('Failed to complete purchase:', error);
        const errorMessage = error instanceof Error ? error.message : '购买处理失败';
        setError(errorMessage);
        onPurchaseFailed?.(error as PurchaseError);

        sendMessageToWebView?.({
          type: 'PURCHASE_ERROR',
          data: { error: errorMessage },
        });

        Alert.alert('购买失败', errorMessage);
      } finally {
        setPurchasing(false);
        isProcessingRef.current = false;
      }
    },
    onPurchaseError: (error) => {
      setPurchasing(false);
      isProcessingRef.current = false;

      if (error.code !== ErrorCode.UserCancelled) {
        console.error('Purchase error:', error.message);
        setError(error.message);
        onPurchaseFailed?.(error);

        sendMessageToWebView?.({
          type: 'PURCHASE_ERROR',
          data: { error: error.message, code: error.code },
        });

        Alert.alert('购买错误', error.message);
      } else {
        console.log('Purchase cancelled by user');
        sendMessageToWebView?.({
          type: 'PURCHASE_CANCELLED',
        });
      }
    },
  });

  // 获取产品列表
  useEffect(() => {
    if (connected && productIds.length > 0) {
      setLoading(true);
      setError(null);

      fetchProducts({ skus: productIds, type: productType as any })
        .then(() => {
          setLoading(false);
          console.log('Products fetched successfully');
        })
        .catch((err) => {
          setLoading(false);
          const errorMessage = err instanceof Error ? err.message : '获取产品失败';
          setError(errorMessage);
          console.error('Failed to fetch products:', err);
        });
    }
  }, [connected, productIds.join(','), productType]);

  // 发起购买
  const handlePurchase = useCallback(
    async (productId: string) => {
      if (!connected) {
        const errorMsg = '商店未连接，请稍后重试';
        setError(errorMsg);
        Alert.alert('错误', errorMsg);
        return;
      }

      if (purchasing) {
        console.log('Purchase already in progress');
        return;
      }

      setPurchasing(true);
      setError(null);

      try {
        sendMessageToWebView?.({
          type: 'PURCHASE_STARTED',
          data: { productId },
        });

        if (productType === 'in-app') {
          await requestPurchase({
            request: {
              ios: {
                sku: productId,
              },
              android: {
                skus: [productId],
              },
            },
            type: 'in-app',
          });
        } else {
          await requestPurchase({
            request: {
              ios: {
                sku: productId,
              },
              android: {
                skus: [productId],
              },
            },
            type: 'subs',
          });
        }
      } catch (error) {
        setPurchasing(false);
        const errorMessage = error instanceof Error ? error.message : '购买失败';
        console.error('Purchase failed:', error);
        setError(errorMessage);
        Alert.alert('购买失败', errorMessage);
      }
    },
    [connected, purchasing, requestPurchase, sendMessageToWebView]
  );

  // 恢复购买
  const restorePurchases = useCallback(async () => {
    if (!connected) {
      const errorMsg = '商店未连接，请稍后重试';
      setError(errorMsg);
      Alert.alert('错误', errorMsg);
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const availablePurchases = await getAvailablePurchasesAPI() || [];
      console.log('Available purchases:', availablePurchases);

      if (availablePurchases.length === 0) {
        Alert.alert('提示', '没有可恢复的购买记录');
      } else {
        // TODO: 验证恢复的购买并更新用户状态
        sendMessageToWebView?.({
          type: 'PURCHASES_RESTORED',
          data: { purchases: availablePurchases },
        });

        Alert.alert('成功', `已恢复 ${availablePurchases.length} 个购买记录`);
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '恢复购买失败';
      console.error('Restore purchases failed:', error);
      setError(errorMessage);
      Alert.alert('恢复失败', errorMessage);
    } finally {
      setLoading(false);
    }
  }, [connected, sendMessageToWebView]);

  // 根据 productId 获取产品信息
  const getProduct = useCallback(
    (productId: string) => {
      return products.find((p) => p.id === productId);
    },
    [products]
  );

  // 清除错误
  const clearError = useCallback(() => {
    setError(null);
  }, []);

  return {
    // 状态
    connected,
    products,
    loading,
    error,
    purchasing,
    
    // 方法
    handlePurchase,
    restorePurchases,
    getProduct,
    clearError,
  };
}
