import { XStack, YStack, Image, View } from 'tamagui';
import CustomText from '@/components/common/CustomText';
import { StyleSheet, TouchableOpacity, Alert, AppState } from 'react-native';
import { MMKV } from 'react-native-mmkv';
import { router } from 'expo-router';
import { showSuccess, showError, showInfo } from '@/utils/ui/toast.js';
import { ServeGetECardInfoByPhone } from '@/api/personal';
import { useState, useRef, useEffect } from 'react';
import { useAppStore } from '@/stores';

// UI组件
import LoadingSpinner from '@/components/ui/LoadingSpinner';

// 引入屏幕适配
import { wp, sp } from '@/utils/ui/screenUtils';
// 引入国际化
import { useTranslation } from '@/node_modules/react-i18next';

// 引入store
import { useAuthStore } from '@/stores/auth';
import { useClockInStore } from '@/stores/clockIn';
// WeChat API
import ExpoWeChat from 'expo-wechat';

const UserTools = () => {
    // 获取主色
    const primaryColor = useAppStore(s => s.primary)

    // 国际化
    const { t } = useTranslation('personal');

    // 获取当前用户信息
    const user = useAuthStore(state => state.getUser());

    // 仅订阅所需的 actions，避免订阅整个 store 导致无关重渲染
    const logout = useAuthStore(s => s.logout);
    const clearToken = useAuthStore(s => s.clearToken);
    const clearApiResults = useClockInStore(s => s.clearApiResults);
    const setClockInList = useClockInStore(s => s.setClockInList);
    const setLocation = useClockInStore(s => s.setLocation);

    // 拉起微信分享名片loading
    const [isShareLoading, setIsShareLoading] = useState(false);
    // 分享流程稳定性控制：AppState 监听与计时器
    const shareInFlightRef = useRef(false);
    const handshakeSeenRef = useRef(false);
    const activeStabilityTimerRef = useRef(null);
    const globalTimeoutRef = useRef(null);
    const ACTIVE_STABILITY_MS = 1800; // 前台稳定性窗口，避免误杀握手
    const GLOBAL_TIMEOUT_MS = 12000;  // 全局兜底，避免卡死

    const clearShareTimers = () => {
        if (activeStabilityTimerRef.current) {
            clearTimeout(activeStabilityTimerRef.current);
            activeStabilityTimerRef.current = null;
        }
        if (globalTimeoutRef.current) {
            clearTimeout(globalTimeoutRef.current);
            globalTimeoutRef.current = null;
        }
    };

    const finishShare = () => {
        setIsShareLoading(false);
        shareInFlightRef.current = false;
        handshakeSeenRef.current = false;
        clearShareTimers();
    };

    useEffect(() => {
        const sub = AppState.addEventListener('change', (nextState) => {
            if (!shareInFlightRef.current) return;

            // 离开应用（进入后台/非活跃）说明在分享或继续切到微信；标记握手，但不取消 loading
            if (nextState === 'background' || nextState === 'inactive') {
                handshakeSeenRef.current = true;
                if (activeStabilityTimerRef.current) {
                    clearTimeout(activeStabilityTimerRef.current);
                    activeStabilityTimerRef.current = null;
                }
                return;
            }

            // 回到前台：如果之前发生过握手，开启前台稳定性窗口，窗口结束仍未有回调则判定分享已中断
            if (nextState === 'active' && handshakeSeenRef.current) {
                if (activeStabilityTimerRef.current) {
                    clearTimeout(activeStabilityTimerRef.current);
                }
                activeStabilityTimerRef.current = setTimeout(() => {
                    if (shareInFlightRef.current) {
                        finishShare();
                        // showInfo('分享已中断或取消');
                    }
                }, ACTIVE_STABILITY_MS);
            }
        });

        return () => {
            sub.remove?.();
            clearShareTimers();
            shareInFlightRef.current = false;
            handshakeSeenRef.current = false;
        };
    }, []);

    // 清除缓存
    const handleClearCache = () => {
        showSuccess('刷新成功');
    };

    // 清除缓存(留档，暂不使用)
    const handleClearCache_ = () => {
        Alert.alert(
            '清除缓存',
            '确定要清除所有缓存数据吗？此操作不可恢复。',
            [
                {
                    text: '取消',
                    style: 'cancel',
                },
                {
                    text: '确定',
                    style: 'destructive',
                    onPress: () => {
                        try {
                            // 清除MMKV存储
                            const storage = new MMKV();
                            storage.clearAll();

                            // 重置store状态
                            clearApiResults();
                            setClockInList([]);
                            setLocation(null);

                            // 退出登录
                            logout();
                            clearToken();

                            Alert.alert('成功', '缓存已清除，请重新登录');
                            router.replace('/login');
                        } catch (error) {
                            console.error('清除缓存错误:', error);
                            Alert.alert('错误', '清除缓存失败，请重试');
                        }
                    },
                },
            ]
        );
    };

    // 分享名片
    const handleShareCard = async () => {
        setIsShareLoading(true);
        // 启动分享流程与兜底计时器
        shareInFlightRef.current = true;
        handshakeSeenRef.current = false;
        if (globalTimeoutRef.current) {
            clearTimeout(globalTimeoutRef.current);
        }
        globalTimeoutRef.current = setTimeout(() => {
            if (shareInFlightRef.current) {
                finishShare();
                // showInfo('分享可能未完成，请重试');
            }
        }, GLOBAL_TIMEOUT_MS);

        try {
            const installed = await ExpoWeChat.isWXAppInstalled()
            if (!installed) {
                showInfo('未安装微信，无法分享')
                finishShare();
                return
            }

            // 前置：手机号判空
            if (!user?.TelNum) {
                showInfo('未获取到手机号，无法分享')
                finishShare();
                return
            }

            const params = {
                phone: user?.TelNum
            }
            const res = await ServeGetECardInfoByPhone(params)

            // res 判空与状态检查
            if (!res) {
                showError('网络异常，请稍后重试')
                finishShare();
                return
            }
            if (res?.status !== 0) {
                showError(res?.msg || res?.message || '获取名片信息失败')
                finishShare();
                return
            }

            const resData = res.data || {}
            const uid = resData?.uid
            const userType = resData?.userType
            const name = resData?.name

            // 关键字段校验
            if (!uid || !userType) {
                showError('名片信息不完整，无法分享')
                finishShare();
                return
            }

            const ret = await ExpoWeChat.shareMiniProgram({
                id: 'gh_97094c34debd',
                type: 'release',
                path: `/pages/mine/index?uid=${uid}&userType=${userType}`,
                scene: 'session',
                title: name ? `${name}的电子名片` : '电子名片',
                thumbBase64OrImageUri: 'https://e-cdn.fontree.cn/fonchain-main/prod/image/139/avatar/ababc42c-7654-47f8-b22b-29dc589c71f0.png',
                webpageUrl: process.env.EXPO_PUBLIC_WECHAT_UNIVERSAL_LINK,
            })

            console.log('WeChat shareMiniProgram result:', ret)

            if (ret) {
                finishShare();
            } else {
                showError('分享失败，请重试')
                finishShare();
            }
        } catch (e) {
            console.warn('WeChat mini program share failed', e)
            showError('分享失败，请重试')
            finishShare();
        }
    };

    return (
        <XStack style={styles.userToolArea}>
            <TouchableOpacity style={{flex:1}} onPress={handleShareCard} disabled={isShareLoading}>
                <View style={styles.shareCardContainer}>
                    <XStack style={styles.userToolItem}>
                        <YStack style={styles.toolItemBox}>
                            <CustomText style={styles.toolItemTitle}>{t('tools.myCard')}</CustomText>
                            <CustomText style={styles.toolItemDesc}>{t('tools.myCard_desc')}</CustomText>
                        </YStack>
                        <Image style={styles.toolItemIcon} source={require('@/assets/images/personal/myCard.png')} />
                    </XStack>
                    {isShareLoading && (
                        <YStack style={styles.shareCardSpinner}>
                            <LoadingSpinner size={wp(20)} color={primaryColor} animating={isShareLoading} />
                        </YStack>
                    )}
                </View>
            </TouchableOpacity>
            <View style={styles.separatorLine}></View>
            <TouchableOpacity style={{flex:1}} onPress={handleClearCache}>
                <XStack style={styles.userToolItem}>
                    <YStack style={styles.toolItemBox}>
                        <CustomText style={styles.toolItemTitle}>{t('tools.refreshCache')}</CustomText>
                        <CustomText style={styles.toolItemDesc}>{t('tools.refreshCache_desc')}</CustomText>
                    </YStack>
                    <Image style={styles.toolItemIcon} source={require('@/assets/images/personal/clearCache.png')} />
                </XStack>
            </TouchableOpacity>
        </XStack>
    )
}

export default UserTools;

const styles = StyleSheet.create({
    userToolArea: {
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    shareCardContainer: {
        position: 'relative',
        flex: 1,
    },
    shareCardSpinner: {
        position: 'absolute',
        left: 0,
        top: 0,
        bottom: 0,
        right: 0,
        zIndex: 2,
        backgroundColor: 'rgba(255,255,255,0.8)',
        alignItems: 'center',
        justifyContent: 'center',
    },
    userToolItem: {

        gap: wp(20),
        paddingHorizontal: wp(14),
        paddingVertical: wp(4),
        alignItems: 'center',
        justifyContent: 'space-between',
        zIndex: 1,
        position: 'relative',
    },
    toolItemBox: {
        alignItems: 'flex-start',
        justifyContent: 'center',
    },
    toolItemTitle: {
        fontSize: sp(14),
        fontFamily: 'Medium',
        color: '#191919',
        lineHeight: wp(20),
     
    },
    toolItemDesc: {
        fontSize: sp(12),
        fontFamily: 'Regular',
        color: '#B4B4B4',
        lineHeight: wp(17),
   
    },
    toolItemIcon: {
        position: 'absolute',
        width: wp(40),
        height: wp(40),
        right: wp(15),
    
    },
    separatorLine: {
        width: wp(1),
        height: wp(40),
        backgroundColor: '#F8F8F8',
    }
})
