import React, { useEffect } from 'react';
import { Redirect, router, useRouter } from 'expo-router';

import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { useToken } from '@/context/AppProvider';
import { Request } from '@/services/request';


export default function OnboardStartScreen() {
    const { token, isLoading } = useToken();
    const router = useRouter();

    const loadingScreen = () => (
        <ThemedView>
            <ThemedText>Laden...</ThemedText>
        </ThemedView>
    );

    useEffect( () => {
        const fetchData = async () => {
            const response = await Request.post( 'sessions/get', { token: token } );
            if (response.success) {
                // @ts-ignore
                router.replace( '/(tabs)/settings' );
            } else {
                router.replace( '/(onboarding)/start' );
            }
        };

        if (!isLoading && token) {
            fetchData();
        }
    }, [ isLoading, token, router ] );

    if (isLoading) {
        return loadingScreen();
    }

    if (!token) {
        return <Redirect href="/(onboarding)/start"/>;
    }

    return loadingScreen();
}
