import ReturnArrowSvg from '@/assets/icons/svg/returnArrow.svg';
import StarSvg from '@/assets/icons/svg/whiteStart.svg';
import PrivacyModal from '@/components/owner/qualification/privacy';
import Normal from '@/components/owner/rights/normal';
import PayTypeModal from '@/components/owner/rights/payType';
import Premium, { PayItem } from '@/components/owner/rights/premium';
import ProRights from '@/components/owner/rights/proRights';
import { createOrder, createPayment, getPAy, payFailure, paySuccess } from '@/components/owner/rights/utils';
import { ThemedText } from '@/components/ThemedText';
import { CreateOrder } from '@/types/personal-info';
import { ErrorCode, getAvailablePurchases, getPurchaseHistories, ProductPurchase, useIAP } from 'expo-iap';
import { useLocalSearchParams, useRouter } from "expo-router";
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Image, ScrollView, StyleSheet, TouchableOpacity, View } from 'react-native';
import { useSafeAreaInsets } from "react-native-safe-area-context";

export default function Rights() {
    const insets = useSafeAreaInsets();
    const router = useRouter();
    const { t } = useTranslation();
    const {
        connected,
        products,
        subscriptions,
        currentPurchase,
        currentPurchaseError,
        requestProducts,
        requestPurchase,
        finishTransaction,
        validateReceipt,
    } = useIAP();
    // 购买方式弹窗
    const [showPayType, setShowPayType] = useState<boolean>(false);
    // 选择购买方式
    const [payChoice, setPayChoice] = useState<'ApplePay'>('ApplePay');
    // 获取路由参数
    const { credit } = useLocalSearchParams<{
        credit: string;
    }>();
    // 普通用户，会员
    const [userType, setUserType] = useState<'normal' | 'premium'>('normal');

    // 选择权益方式
    const [payType, setPayType] = useState<string>('');

    // 用户协议弹窗打开
    const [showTerms, setShowTerms] = useState<boolean>(false);

    // 调接口获取支付信息
    const [premiumPay, setPremiumPay] = useState<PayItem[]>();
    const [loading, setLoading] = useState<boolean>(false);

    // 确认支付
    const [confirmPay, setConfirmPay] = useState<boolean>(false);

    // 查看历史订单
    const fetchPurchaseHistory = async () => {
        try {
            const purchaseHistories = await getPurchaseHistories();
            console.log('Purchase history fetched:', purchaseHistories);
        } catch (error) {
            console.error('Failed to fetch purchase history:', error);
        }
    };

    // 恢复购买
    const restorePurchases = async () => {
        try {
            const purchases = await getAvailablePurchases();
            console.log('Available purchases:', purchases);
            // Process and validate restored purchases
            for (const purchase of purchases) {
                await validateAndGrantPurchase(purchase);
            }
        } catch (error) {
            console.error('Restore failed:', error);
        }
    };

    // 处理购买
    const handlePurchase = async (sku: string, transaction_id: string) => {
        console.log('handlePurchase', sku);
        try {
            const res = await requestPurchase({
                request: {
                    ios: {
                        sku: "MEMBERSHIP_PRO_QUARTERLY",
                        andDangerouslyFinishTransactionAutomaticallyIOS: false,
                    },
                },
            });
            // 支付成功
            paySuccess(transaction_id, res?.transaction_id || "")
        } catch (error: any) {
            console.log('Purchase failed:', error);
            // 支付失败
            payFailure(transaction_id, ErrorCode[error?.code as keyof typeof ErrorCode || "E_UNKNOWN"])
        }
    };

    // 获取苹果订单信息
    useEffect(() => {
        console.log('connected', connected);

        if (!connected) return;

        const initializeStore = async () => {
            try {
                await requestProducts({ skus: ["MEMBERSHIP_PRO_QUARTERLY"], type: 'subs' });
                console.log("subscriptions", subscriptions);
            } catch (error) {
                console.error('Failed to initialize store:', error);
            }
        };

        initializeStore();
    }, [connected]);

    // 初始化获取产品项
    useEffect(() => {
        setLoading(true);
        getPAy().then(({ bestValue, payInfo }) => {
            setPayType(bestValue?.product_code)
            setPremiumPay([bestValue, ...payInfo?.filter((item) => item.product_code !== bestValue?.product_code)]);
            setLoading(false);
        }).catch(() => {
            setLoading(false);
        })
    }, []);

    // 用户确认购买时，进行 创建订单，创建支付 接口调用
    useEffect(() => {
        console.log('confirmPay', confirmPay);
        if (confirmPay) {
            // 创建订单
            createOrder(premiumPay?.filter((item) => item.product_code === payType)?.[0]?.id || 1, 1).then((res: CreateOrder) => {
                // 创建支付
                createPayment(res?.id || "", payChoice).then((res) => {
                    console.log("createPayment", res);
                    console.log("payType", payType);
                    // 苹果支付
                    handlePurchase(payType, res?.transaction_id || "")
                }).catch((err) => {
                    console.log("createPayment", err);
                })
            }).catch((err) => {
                console.log("createOrder", err);
            })
        }
    }, [confirmPay]);

    useEffect(() => {
        if (currentPurchase) {
            console.log('currentPurchase', currentPurchase);
        }
    }, [currentPurchase]);

    useEffect(() => {

        console.log('currentPurchaseError', currentPurchaseError);

    }, [currentPurchaseError]);
    return (
        <View style={{ flex: 1 }}>
            <ScrollView style={[styles.container, { paddingTop: insets.top, paddingBottom: insets.bottom + 80 }]}>
                {/* 导航栏 */}
                <View
                    style={styles.header}
                >
                    <TouchableOpacity onPress={() => { router.push('/owner') }} style={{ padding: 16 }}>
                        <ReturnArrowSvg />
                    </TouchableOpacity>
                    <ThemedText style={styles.headerTitle}>
                        {t('rights.title', { ns: 'personal' })}
                    </ThemedText>
                    <ThemedText className='opacity-0'>123</ThemedText>
                </View>
                {/* 会员卡 */}
                <View style={styles.card}>
                    {userType === 'normal' ? (
                        <Image source={require('@/assets/images/png/owner/normal.png')} style={{ height: 150, objectFit: 'cover', width: '100%' }} />
                    ) : (
                        <Image source={require('@/assets/images/png/owner/pro.png')} style={{ height: 150, objectFit: 'cover', width: '100%' }} />
                    )}
                    <View style={styles.cardContent}>
                        <View style={styles.cardinfo}>
                            <ThemedText style={styles.cardTitle}>
                                {t('rights.purchase', { ns: 'personal' })}
                            </ThemedText>
                            <View style={styles.cardPoints}>
                                <StarSvg />
                                <ThemedText style={styles.cardPointsText}>{credit}</ThemedText>
                            </View>
                        </View>
                    </View>
                </View>

                {/* 会员信息 */}
                <View style={styles.info}>
                    {/* 切换按钮 */}
                    <View style={styles.switchButton}>
                        <TouchableOpacity
                            onPress={() => { setUserType("normal") }}
                            style={[styles.switchButtonItem, { backgroundColor: userType === 'normal' ? "#FFB645" : "#fff", borderColor: userType === 'normal' ? "#FFB645" : "#E2793F" }]}
                        >
                            <ThemedText style={{ color: userType === 'normal' ? "#fff" : "#E2793F" }}> {t('rights.free', { ns: 'personal' })}</ThemedText>
                        </TouchableOpacity>
                        <TouchableOpacity
                            onPress={() => { setUserType("premium") }}
                            style={[styles.switchButtonItem, { backgroundColor: userType === 'premium' ? "#E2793F" : "#fff", borderColor: userType === 'premium' ? "#E2793F" : "#E2793F" }]}
                        >
                            <ThemedText style={{ color: userType === 'premium' ? "#fff" : "#E2793F" }}>{t('rights.premium', { ns: 'personal' })}</ThemedText>
                        </TouchableOpacity>
                    </View>
                    {/* 普通权益 */}
                    <Normal setUserType={setUserType} style={{ display: userType === 'normal' ? "flex" : "none" }} />
                    {/* 会员权益 */}
                    <Premium setPayType={setPayType} setShowTerms={setShowTerms} payType={payType} premiumPay={premiumPay} loading={loading} style={{ display: userType === 'normal' ? "none" : "flex" }} />
                </View>
                {/* 支付方式 */}
                <PayTypeModal setConfirmPay={setConfirmPay} modalVisible={showPayType} setModalVisible={setShowPayType} payChoice={payChoice} setPayChoice={setPayChoice} />
                {/* 会员权益信息 */}
                <View style={{ flex: 1, marginBottom: 80 }}>
                    <ProRights style={{ display: userType === 'normal' ? "none" : "flex" }} />
                </View>
                {/* <ApplePay /> */}
            </ScrollView>
            {/* 付费按钮 */}
            <View style={{
                padding: 16,
                backgroundColor: '#fff',
                borderTopWidth: 1,
                borderTopColor: '#eee',
                position: 'absolute',
                bottom: 0,
                left: 0,
                right: 0,
                display: userType === 'normal' ? "none" : "flex"
            }}>
                <TouchableOpacity
                    style={styles.goPay}
                    onPress={async () => {
                        setUserType('premium');
                        // handlePurchase(payType);
                        setShowPayType(true)
                    }}
                    activeOpacity={0.8}
                >
                    <ThemedText style={{ color: '#fff', fontWeight: '700', fontSize: 14 }}>
                        {t('rights.subscribe', { ns: 'personal' })}
                    </ThemedText>
                </TouchableOpacity>
                <TouchableOpacity
                    onPress={async () => {
                        setShowTerms(true);
                    }}
                    activeOpacity={0.8}
                >
                    <ThemedText style={{ color: '#AC7E35', fontWeight: '400', fontSize: 11, textDecorationLine: 'underline', textAlign: 'center' }}>
                        {t('rights.terms', { ns: 'personal' })}
                    </ThemedText>
                </TouchableOpacity>
            </View>
            {/* 协议弹窗 */}
            <PrivacyModal modalVisible={showTerms} setModalVisible={setShowTerms} type={"user"} />
        </View>
    );
}

const styles = StyleSheet.create({
    payChoice: {
        width: 20,
        height: 20,
        borderRadius: 15,
        alignItems: 'center',
        justifyContent: 'center',
    },
    paymentMethod: {
        marginHorizontal: 16,
        marginVertical: 16,
        borderRadius: 12,
        backgroundColor: '#fff',
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.25,
        shadowRadius: 5,
        elevation: 5,
    },
    goPay: {
        backgroundColor: '#E2793F',
        borderRadius: 24,
        paddingVertical: 10,
        display: "flex",
        alignItems: "center",
        width: "100%",
    },
    switchButton: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        gap: 16,
        marginBottom: 16
    },
    switchButtonItem: {
        width: "48%",
        borderRadius: 24,
        paddingVertical: 6,
        display: "flex",
        alignItems: "center",
        borderWidth: 1
    },
    info: {
        marginHorizontal: 16,
        marginVertical: 16,
        padding: 16,
        borderRadius: 12,
        backgroundColor: '#fff',
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.25,
        shadowRadius: 5,
        elevation: 5,
    },
    container: {
        flex: 1,
        backgroundColor: 'white',
    },
    header: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginVertical: 16,
    },
    headerTitle: {
        fontSize: 20,
        fontWeight: '700',
        color: '#4C320C',
    },
    card: {
        marginHorizontal: 16,
        marginVertical: 16,
        backgroundColor: '#FFB645',
        borderRadius: 12,
    },
    cardContent: {
        position: 'absolute',
        top: 0,
        right: 0,
        bottom: 0,
        left: 0,
        padding: 16,
        justifyContent: 'space-between'
    },
    cardinfo: {
        alignItems: 'flex-end',
    },
    cardTitle: {
        fontSize: 12,
        fontWeight: '700',
        color: '#E2793F',
        backgroundColor: '#fff',
        paddingHorizontal: 8,
        paddingVertical: 2,
        borderRadius: 20,
        textAlign: 'center',
        marginBottom: 24
    },
    cardPoints: {
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        gap: 4
    },
    cardPointsText: {
        fontSize: 32,
        fontWeight: '700',
        color: '#4C320C',
        lineHeight: 32
    }
});
function validateAndGrantPurchase(purchase: ProductPurchase) {
    throw new Error('Function not implemented.');
}

