
import { kIsAndroid, kIsIOS } from "@/utils/tools";
import { View, Text, Image } from "@tarojs/components";
import { useEffect, useState } from "react";
import { FlatList, Pressable } from "react-native";
import Purchases from 'react-native-purchases'
import { useSelector } from "react-redux";
import './product_list.scss'
import { ColorType } from "@/context/themes/color";
import { payInfo } from "@/services/user";
import Taro from "@tarojs/taro";

let useNavigation;
if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
}
export default function ProductList() {

    const [packages, setPackages] = useState([]);
    const user = useSelector((state: any) => state.user);
    // - State for displaying an overlay view
    const [isPurchasing, setIsPurchasing] = useState(false);
    const [errorCode,setErrorCode] = useState<any>(-1)

    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    useEffect(() => {
        console.log(user)
        if (process.env.TARO_ENV == 'rn') {
            if (kIsIOS) {
                Purchases.configure({
                    apiKey: 'appl_FNFYDLwHZlXzqrKJFlErWXUHGwx',
                    appUserID: user.id
                })
            }
            else if (kIsAndroid) {
                Purchases.configure({
                    apiKey: 'goog_cyJSYOsnZpNqsUbCsHSdhqQdQwe',
                    appUserID: user.id
                })
            }
            getProducts();
            // console.log('aaaa')
            // setTimeout(() => {
            //     // getProducts();
            //     hi()
            // }, 2000)

        }
    }, [])

    async function getProducts() {
        try {
            const offerings = await Purchases.getOfferings();
            console.log('product list offerings', offerings)
            console.log('product list detail', (offerings as any).current.availablePackages[1])

            if (offerings.current !== null && offerings.current.availablePackages.length !== 0) {
                setPackages((offerings as any).current.availablePackages);
            }
        } catch (e) {
            console.log(e.message)
        }
    }


    async function hi() {
        try {
            // 启动购买流程
            const purchaseResult = await Purchases.purchaseProduct('pro_lifelong_test');
            console.log(purchaseResult);
            // 检查购买是否成功
            // setIsSubscribed(purchaseResult.purchaserInfo.activeSubscriptions.length > 0);
        } catch (error) {
            console.error('Purchase error:', error);
        }
    }

    async function pay(item: any) {
        setIsPurchasing(true);
        try {
            const { customerInfo, productIdentifier, transaction } = await Purchases.purchasePackage(item);
            payInfo({
                customerInfo,
                productIdentifier,
                transaction
            }).then(res => {
                global.paySuccess()
                if (process.env.TARO_ENV == 'rn') {
                    navigation.pop(1)
                }
                else {
                    Taro.navigateBack({
                        delta: 1
                    })
                }
            });
            console.log('result', customerInfo)
        } catch (e) {
            debugger
            setErrorCode(e.code)
            if (e.code === Purchases.PURCHASES_ERROR_CODE.PURCHASE_CANCELLED_ERROR) {

            }
        } finally {
            setIsPurchasing(false);
        }
    }

    return <View>
        <View style={{ height: 40 }} />
        {
            packages.map((item, index) => {
                return <View className="product_item" key={index} onClick={() => pay(item)}>
                    <Text className="product_title" style={{ color: ColorType.fast }}>{(item as any).product.title}</Text>
                    <Text style={{ color: '#fff', fontSize: 16, marginTop: 5, marginBottom: 5 }}>{(item as any).product.description}</Text>
                    <View style={{ flexDirection: 'row', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Text className="product_price">{(item as any).product.priceString}</Text>
                        <Image style={{ width: 24, height: 24 }} src={require('@/assets/images/arrow3.png')} />
                    </View>

                </View>
            })
        }
        {/* <FlatList
            data={packages}
            renderItem={({ item }) => <View className="product_item" onClick={() => pay(item)}>
                <Text className="product_title" style={{ color: ColorType.fast }}>{(item as any).product.title}</Text>
                <Text style={{ color: '#fff', fontSize: 16, marginTop: 5, marginBottom: 5 }}>{(item as any).product.description}</Text>
                <View style={{ flexDirection: 'row', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Text className="product_price">{(item as any).product.priceString}</Text>
                    <Image style={{width:24,height:24}} src={require('@/assets/images/arrow3.png')} />
                </View>

            </View>}
            keyExtractor={(item) => (item as any).identifier}

        /> */}

        {
            isPurchasing && <Text style={{ color: '#fff', fontSize: 40 }}>正在付款</Text>
        }
        {
            errorCode!=-1 && <Text style={{ color: '#fff', fontSize: 40 }}>出错了，错误代码{errorCode}</Text>
        }
    </View>
}