import { Card, YStack, View, Switch } from 'tamagui';
import CustomText from '@/components/common/CustomText';
import { StyleSheet, AppState } from 'react-native';
import { Image as ExpoImage } from 'expo-image';
import { useMemo, useState, useCallback, useEffect, useRef } from 'react';
import { Check } from '@tamagui/lucide-icons';
import * as Application from 'expo-application';
import Constants from 'expo-constants';
import * as Updates from 'expo-updates';
import { router, useFocusEffect } from 'expo-router';
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useAppStore } from '@/stores';

//自定义组件
import { CustomSafeArea } from '@/components/common/CustomSafeArea';
import { CustomHeader } from '@/components/common/CustomHeader';

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

// 引入国际化
import { useTranslation } from '@/node_modules/react-i18next';
import { setAppLanguage, getLanguagePreference } from '@/i18n';
// 引入屏幕适配
import { wp, sp } from '@/utils/ui/screenUtils';
// 引入全局弹窗服务
import dialogService from '@/utils/ui/dialogService.js';
import selectService from '@/utils/ui/selectService';
import { useAuthStore } from '@/stores/auth';
// 引入推送获取和设置工具
import { handleToggleAttempt, getCombinedStatus } from '@/utils/core/pushSettings.js';

// 获取应用版本
const displayVersion =
    Updates.manifest?.extra?.displayVersion ??
    Constants.expoConfig?.extra?.displayVersion ??
    Application.nativeApplicationVersion ?? '';
//获取应用名称
const appName =
    Updates.manifest?.extra?.displayAppName ??
    Constants.expoConfig?.extra?.displayAppName ??
    Constants.expoConfig?.name ??
    Application.nativeApplicationName ?? '';

const SettingsAndPrivacyScreen = () => {
    //获取主色
    const primaryColor = useAppStore(s => s.primary)
    const notificationEnabledPersisted = useAppStore(s => s.notificationEnabled)
    const setNotificationEnabledPersist = useAppStore(s => s.setNotificationEnabled)

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

    // 退出登录清空登录状态
    const { logout } = useAuthStore();

    // 消息提醒开关状态（使用持久化的上次有效值作为初始值）
    const [switchChecked, setSwitchChecked] = useState(notificationEnabledPersisted);
    // 切换期间禁用开关，防止重复点击并发
    const [isToggling, setIsToggling] = useState(false);

    // 获取安全区
    const insets = useSafeAreaInsets();
    // 多语言选择
    const [appliedLanguageIndex, setAppliedLanguageIndex] = useState(0);
    
    // 语言选项列表
    const languageList = useMemo(() => [
        { label: tCommon('language.system'), value: 0 },
        { label: tCommon('language.zhCN'), value: 1 },
        { label: tCommon('language.zhTW'), value: 2 },
        { label: tCommon('language.en'), value: 3 },
    ], [tCommon]);

    // 根据 index 映射到偏好值
    const indexToPref = useCallback((idx) => {
        switch (idx) {
            case 1: return 'zh-CN';
            case 2: return 'zh-TW';
            case 3: return 'en';
            case 0:
            default: return 'system';
        }
    }, []);
    const prefToIndex = useCallback((pref) => {
        switch (pref) {
            case 'zh-CN': return 1;
            case 'zh-TW': return 2;
            case 'en': return 3;
            case 'system':
            default: return 0;
        }
    }, []);

    // 初始化：从持久化读取偏好，设置已生效index
    useEffect(() => {
        const pref = getLanguagePreference?.() || 'system';
        const idx = prefToIndex(pref);
        setAppliedLanguageIndex(idx);
    }, [prefToIndex]);

    // 正在用户交互（点击开关并可能跳系统设置）期间，避免 AppState 的刷新覆盖 UI
    const isTogglingRef = useRef(false);

    // 页面聚焦或返回前台时，同步“系统权限和服务端偏好”的有效状态到开关
    useFocusEffect(
        useCallback(() => {
            let mounted = true;
            (async () => {
                const effectiveOn = await getCombinedStatus();
                if (mounted) {
                    if (typeof effectiveOn === 'boolean') {
                        setSwitchChecked(effectiveOn);
                        setNotificationEnabledPersist(effectiveOn);
                    }
                }
            })();
            return () => { mounted = false; };
        }, [])
    );

    // 当应用从后台回到前台（active）时刷新一次（覆盖用户去系统设置手动修改权限/偏好后的场景）
    useEffect(() => {
        const sub = AppState.addEventListener('change', async (state) => {
            if (state === 'active') {
                // 若当前正在执行开关交互（可能刚从系统设置返回，且服务端状态尚未刷新），避免用旧状态覆盖 UI
                if (isTogglingRef.current) return;
                const effectiveOn = await getCombinedStatus();
                if (typeof effectiveOn === 'boolean') {
                    setSwitchChecked(effectiveOn);
                    setNotificationEnabledPersist(effectiveOn);
                }
            }
        });
        return () => { sub?.remove?.(); };
    }, []);

    // 开关点击处理（遵循系统层权限 + 应用内软开关策略）
    const onToggle = useCallback(async (next) => {
        isTogglingRef.current = true;
        setIsToggling(true);
        try {
            const uiChecked = await handleToggleAttempt(!!next);
            if (typeof uiChecked === 'boolean') {
                setSwitchChecked(uiChecked);
                setNotificationEnabledPersist(uiChecked);
            }
            // 若返回 undefined，表示保持未知态：不改动当前 UI
        } finally {
            isTogglingRef.current = false;
            setIsToggling(false);
        }
    }, []);

    // 消息提醒开关节点
    const switchNode = useMemo(() => {
        return (
            <Switch
                id={'msgRemind'}
                size="$4"
                checked={switchChecked}
                onCheckedChange={onToggle}
                disabled={isToggling}
                borderColor={switchChecked ? primaryColor : '#eeeeee'}
                backgroundColor={switchChecked ? primaryColor : '#eeeeee'}>
                <Switch.Thumb animation="calm" style={styles.checkIcon}>
                    {isToggling ? <LoadingSpinner size={wp(16)} color={primaryColor} /> : switchChecked && <Check color={primaryColor} />}
                </Switch.Thumb>
            </Switch>
        )
    }, [switchChecked, primaryColor, onToggle, isToggling]);

    // 模块列表配置
    const modules = useMemo(() => [
        {
            nameKey: 'settingsAndPrivacy.messageRemind',
            hasPointer: false,
            customRightNode: switchNode,
        },
        {
            nameKey: 'settingsAndPrivacy.multiLanguage',
            hasPointer: true,
            customRightNode: (
                <CustomText style={styles.languageText}>
                    {languageList[appliedLanguageIndex]?.label}
                </CustomText>
            ),
            customEvent: async () => {
                const result = await selectService.pick({
                    title: t('settingsAndPrivacy.multiLanguage'),
                    options: languageList,
                    value: appliedLanguageIndex,
                });
                if (result !== null && result !== undefined) {
                    const pref = indexToPref(result);
                    await setAppLanguage(pref);
                    setAppliedLanguageIndex(result);
                }
            },
        },
        {
            nameKey: 'settingsAndPrivacy.personalPhoto',
            hasPointer: true,
            path: '/personal/recentPhoto'
        },
        {
            nameKey: 'settingsAndPrivacy.userServiceAgreement',
            hasPointer: true,
            path: '/agreement/userService'
        },
        {
            nameKey: 'settingsAndPrivacy.privacyPolicy',
            hasPointer: true,
            path: '/agreement/privateInfo'
        },
        {
            nameKey: 'settingsAndPrivacy.about',
            hasPointer: false,
            customLeftNode: (
                <CustomText style={{ fontSize: sp(14), color: '#191919', fontFamily: 'Medium', lineHeight: wp(20) }}>
                    {appName}
                </CustomText>
            ),
            customRightNode: (
                <CustomText style={{ fontSize: sp(14), color: '#747474', fontFamily: 'Medium', lineHeight: wp(20) }}>
                    {tCommon('version')}{displayVersion}
                </CustomText>
            ),
        },
        {
            nameKey: 'settingsAndPrivacy.logout',
            hasPointer: true,
            color: '#BCBCBC',
            customEvent: async () => {
                const result = await dialogService.confirm({
                    content: t('logOut.logoutDialog'),
                })
                if (result) {
                    // 确认退出：清空登录状态并跳转到登录页
                    logout();
                    // 重置导航栈，只保留登录页
                    router.dismissAll();
                    router.replace('/login');
                } else {
                    // 取消退出：无需处理
                }
            }
        },
        {
            nameKey: 'settingsAndPrivacy.deleteAccount',
            hasPointer: true,
            path: '/personal/signOut',
            color: '#BCBCBC',
        }
    ], [tCommon, switchNode, t, logout, languageList, appliedLanguageIndex, indexToPref]);

    return (
        <View flex={1}>
            <ExpoImage
                source={require('@/assets/images/backgrounds/home-bg.webp')}
                style={StyleSheet.absoluteFill}
                contentFit="cover"
                transition={0}
                pointerEvents="none"
                cachePolicy="memory-disk"
            />
            <CustomSafeArea>
                <CustomHeader title={t('modules.settingsAndPrivacy')} />
                <YStack style={styles.container}>
                    <Card style={styles.card}>
                        <ModuleList modules={modules} />
                    </Card>
                </YStack>
            </CustomSafeArea>
        </View>
    )
}

export default SettingsAndPrivacyScreen;

const styles = StyleSheet.create({
    languageText: {
        fontSize: sp(14),
        color: '#747474',
        fontFamily: 'Medium',
        lineHeight: wp(20),
        marginRight: wp(-8),
    },
    container: {
        paddingVertical: wp(10),
        paddingHorizontal: wp(16),
    },
    card: {
        paddingHorizontal: wp(8),
    },
    checkIcon: {
        alignItems: 'center',
        justifyContent: 'center',
    },
})