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

import '@/src/localization/i18n';

import { ThemedView } from '@/src/components/themed/ThemedView';
import { useToken } from '@/src/context/AppProvider';
import { Request } from '@/src/services/request';
import { store } from '@/src/store/store';
import { setSession } from '@/src/store/dataStore';
import NoInternetConnectionScreen from '@/src/components/NoInternet';
import LoadingScreen from '@/src/components/LoadingScreen';

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

    useEffect( () => {
        const fetchData = async () => {
            const response = await Request.post( 'sessions/get', { token: token } );
            if (response.success) {
                // Save to store
                store.dispatch( setSession( response.session ) )

                // Set language
                i18n.changeLanguage( response.session.language );

                // @ts-ignore
                router.replace( '/(tabs)' );
            } else {
                router.replace( '/(onboarding)/start' );
            }
        };

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

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

    return (
        <ThemedView style={{ flex: 1 }}>
            <NoInternetConnectionScreen/>
            <LoadingScreen message={t( "loading" ) + '...'}/>
        </ThemedView>
    )
}
