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

import '@/src/localization/i18n';

import { ThemedText } from '@/src/components/themed/ThemedText';
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';

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

    const loadingScreen = () => (
        <ThemedView>
            <ThemedText>Loading...</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))

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

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