import {useEffect, useState} from "react";
import {LangContext} from "@/context/LangContext";
import StaticAlert from "@/components/ui/StaticAlert";
import {SessionProps} from "@/lib/types/session";
import {getCookie} from "@/lib/utils/cookies";
import {SessionContext} from "@/context/SessionContext";
import {AlertContext} from "@/context/AlertContext";
import {changeLanguage} from "@/lib/i18n";
import * as tauri from '@/lib/tauri';

export default function LoginWrapper({children}: { children: React.ReactNode }) {
    const [locale, setLocale] = useState<'fr' | 'en'>('fr');
    const [errorMessage, setErrorMessage] = useState('');
    const [successMessage, setSuccessMessage] = useState('');
    const [infoMessage, setInfoMessage] = useState('');
    const [warningMessage, setWarningMessage] = useState('');

    const [session, setSession] = useState<SessionProps>({
        isConnected: false,
        user: null,
        accessToken: ''
    })

    useEffect((): void => {
        checkAuthentification().then()
    }, []);

    useEffect((): void => {
        changeLanguage(locale);
    }, [locale]);

    useEffect((): void => {
        if (session.isConnected) {
            tauri.loginSuccess();
        }
    }, [session]);

    async function checkAuthentification(): Promise<void> {
        const language: "fr" | "en" | null = getCookie('lang') as "fr" | "en" | null;
        if (language) {
            setLocale(language);
        }
    }

    return (
        <SessionContext.Provider value={{session: session, setSession: setSession}}>
            <LangContext.Provider value={{lang: locale, setLang: setLocale}}>
                <AlertContext.Provider value={{
                    errorMessage: setErrorMessage,
                    successMessage: setSuccessMessage,
                    infoMessage: setInfoMessage,
                    warningMessage: setWarningMessage
                }}>
                    {children}
                    <div className="fixed top-4 right-4 z-[9999] flex flex-col gap-3">
                        {
                            successMessage && <StaticAlert type={'success'} message={successMessage} onClose={() => {
                                setSuccessMessage('')
                            }}/>
                        }
                        {
                            errorMessage && <StaticAlert type={'error'} message={errorMessage} onClose={() => {
                                setErrorMessage('')
                            }}/>
                        }
                    </div>
                </AlertContext.Provider>
            </LangContext.Provider>
        </SessionContext.Provider>
    )
}
