import IP from '@/assets/icons/svg/ip.svg';
import { registerBackgroundUploadTask, triggerManualUpload } from '@/components/file-upload/backgroundUploader';
import * as MediaLibrary from 'expo-media-library';
import { useRouter } from 'expo-router';
import * as SecureStore from 'expo-secure-store';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Platform, Text, TouchableOpacity, View } from 'react-native';
import { useSafeAreaInsets } from "react-native-safe-area-context";
import MemoList from './memo-list';

export default function HomeScreen() {
    const router = useRouter();
    const { t } = useTranslation();
    const insets = useSafeAreaInsets();
    const [isLoading, setIsLoading] = useState(true);
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    const [token, setToken] = useState('');
    const tokenInterval = useRef<NodeJS.Timeout | number>(null);
    const isMounted = useRef(true);

    const getAuthToken = async (): Promise<string> => {
        let tokenValue = '';
        if (Platform.OS === 'web') {
            tokenValue = localStorage.getItem('token') || '';
        } else {
            tokenValue = (await SecureStore.getItemAsync('token')) || '';
        }
        setToken(tokenValue); // 只在获取到新token时更新状态
        return tokenValue;
    };

    useEffect(() => {
        const checkAuthStatus = async () => {
            try {
                const loggedIn = !!token;
                setIsLoggedIn(loggedIn);

                if (loggedIn) {
                    // 已登录，请求必要的权限
                    const { status } = await MediaLibrary.requestPermissionsAsync();
                    if (status === 'granted') {
                        await registerBackgroundUploadTask();
                        const now = new Date();
                        const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
                        await triggerManualUpload(oneDayAgo, now);
                    }
                    router.replace('/ask');
                }
                setIsLoading(false);
            } catch (error) {
                console.error('检查登录状态出错:', error);
                setIsLoading(false);
            } finally {
                setIsLoading(false);
            }
        };
        checkAuthStatus();
    }, []);

    // 轮询获取token
    useEffect(() => {
        // 如果已经有token，直接返回
        if (token) {
            if (tokenInterval.current) {
                clearInterval(tokenInterval.current);
            }
            return;
        }
        if (!tokenInterval.current) return;
        // 设置轮询 
        tokenInterval.current = setInterval(async () => {
            if (isMounted.current) {
                const currentToken = await getAuthToken();
                // 如果获取到token，清除定时器
                if (currentToken && tokenInterval.current) {
                    clearInterval(tokenInterval.current);
                }
            }
        }, 5000);

        // 返回清理函数
        return () => {
            if (tokenInterval.current) {
                clearInterval(tokenInterval.current);
            }
        };
    }, [token]); // 添加token作为依赖

    if (isLoading) {
        return (
            <View className="flex-1 bg-bgPrimary justify-center items-center">
                <Text className="text-white">加载中...</Text>
            </View>
        );
    }

    return (
        <View className="flex-1">
            {
                isLoggedIn ? <MemoList /> :
                    <View className="flex-1 bg-bgPrimary px-[1rem] h-screen overflow-auto py-[2rem] " style={{ paddingTop: insets.top + 48 }}>
                        {/* 标题区域 */}
                        <View className="items-start mb-10 w-full px-5">
                            <Text className="text-white text-3xl font-bold mb-3 text-left">
                                {t('auth.welcomeAwaken.awaken', { ns: 'login' })}
                                {"\n"}
                                {t('auth.welcomeAwaken.your', { ns: 'login' })}
                                {"\n"}
                                {t('auth.welcomeAwaken.pm', { ns: 'login' })}
                            </Text>
                            <Text className="text-white/85 text-base text-left">
                                {t('auth.welcomeAwaken.slogan', { ns: 'login' })}
                            </Text>
                        </View>

                        {/* Memo 形象区域 */}
                        <View className="items-center">
                            <IP />
                        </View>

                        {/* 介绍文本 */}
                        <Text className="text-white text-base text-center mb-[1rem] leading-6 opacity-90 px-10 -mt-[4rem]">
                            {t('auth.welcomeAwaken.gallery', { ns: 'login' })}
                            {"\n"}
                            {t('auth.welcomeAwaken.back', { ns: 'login' })}
                        </Text>

                        {/* 唤醒按钮 */}
                        <TouchableOpacity
                            className="bg-white rounded-full px-10 py-4 shadow-[0_2px_4px_rgba(0,0,0,0.1)] w-full items-center"
                            onPress={async () => {
                                router.push('/login')
                            }}
                            activeOpacity={0.8}
                        >
                            <Text className="text-[#4C320C] font-bold text-lg">
                                {t('auth.welcomeAwaken.awake', { ns: 'login' })}
                            </Text>
                        </TouchableOpacity>
                    </View>
            }
        </View>
    );
}