import { checkAuthStatus } from '@/lib/auth';
import { registerBackgroundUploadTask } from '@/lib/background-uploader/automatic';
import * as MediaLibrary from 'expo-media-library';
import { useRouter } from 'expo-router';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Text, 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);

    useEffect(() => {
        const doCheck = async () => {
            setIsLoading(true);
            const authed = await checkAuthStatus(router, async () => {
                setIsLoggedIn(true);
                // 已登录，请求必要的权限及上传
                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');
            });
            if (!authed) setIsLoggedIn(false);
            setIsLoading(false);
        };
        doCheck();
    }, []);

    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>
    );
}