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

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


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) {
                // Save to store
                store.dispatch(setSession(response.session))

                // @ts-ignore
                router.replace( '/(tabs)' );
            } 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();
}
