import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import Purchases from 'react-native-purchases';

import { MembershipModal } from '@/components/model/MembershipModal';
import { logger } from '@/utils/logger';

type MembershipModalOptions = {
  onPurchaseSuccess?: () => void;
};

interface MembershipModalContextValue {
  openMembershipModal: (options?: MembershipModalOptions) => void;
  closeMembershipModal: () => void;
}

const MembershipModalContext = createContext<MembershipModalContextValue | null>(null);

export function MembershipModalProvider({ children }: { children: React.ReactNode }) {
  const [visible, setVisible] = useState(false);
  const [pendingSuccessCallback, setPendingSuccessCallback] = useState<(() => void) | undefined>();
  const [isInitialized, setIsInitialized] = useState(false);

  useEffect(() => {
    // 直接使用生产环境的 API Key，避免环境变量问题
    const iosApiKey = 'appl_lmVvuLWFlXlrEsnvxMzTnKapqcc';

    const initializeRevenueCat = async () => {
      try {
        // 检查是否已经配置过，避免重复配置
        if (!isInitialized) {
          await Purchases.configure({ apiKey: iosApiKey });
          setIsInitialized(true);
          console.log('[MembershipModalProvider] RevenueCat SDK 初始化成功');
        }
      } catch (error) {
        console.error('[MembershipModalProvider] RevenueCat SDK 初始化失败:', error);
        // 初始化失败时不阻止应用正常运行
      }
    };

    initializeRevenueCat();
  }, [isInitialized]);

  const openMembershipModal = useCallback((options?: MembershipModalOptions) => {
    setPendingSuccessCallback(() => options?.onPurchaseSuccess);
    setVisible(true);
  }, []);

  const closeMembershipModal = useCallback(() => {
    setVisible(false);
    setPendingSuccessCallback(undefined);
  }, []);

  const handlePurchaseSuccess = useCallback(() => {
    pendingSuccessCallback?.();
  }, [pendingSuccessCallback]);

  const contextValue = useMemo(
    () => ({
      openMembershipModal,
      closeMembershipModal,
    }),
    [closeMembershipModal, openMembershipModal],
  );

  return (
    <MembershipModalContext.Provider value={contextValue}>
      {children}
      <MembershipModal
        visible={visible}
        onClose={closeMembershipModal}
        onPurchaseSuccess={handlePurchaseSuccess}
      />
    </MembershipModalContext.Provider>
  );
}

export function useMembershipModal(): MembershipModalContextValue {
  const context = useContext(MembershipModalContext);

  if (!context) {
    logger.error('useMembershipModal must be used within a MembershipModalProvider');
    // 抛出错误而不是返回 undefined，确保类型安全
    throw new Error('useMembershipModal must be used within a MembershipModalProvider');
  }

  return context;
}
