import { useKeycloak } from '@react-keycloak/web'
import { useEffect } from 'react';
import { Admin, Athlete, Coach, User } from '../classes';
import { useLocalData } from '../context/useLocalData';
import { loginOrRegister, postAthlete } from '../requetes';
import { clearAuthToken, setAuthToken } from '../api';
import { AthleteDTO } from '../classesDTO';

export const Login =() =>{
    const {user,setUser} = useLocalData()
    const { keycloak } = useKeycloak();

    /*useEffect(() => {
        const syncAndLoadUser = async () => {
            if (keycloak.authenticated && keycloak.token && keycloak.tokenParsed) {
                try {
                    const newAthlete: Athlete = new Athlete();
                    newAthlete.keycloakId = keycloak.tokenParsed.sub || "";
                    newAthlete.email = keycloak.tokenParsed.email || "";
                    newAthlete.nom = keycloak.tokenParsed.family_name || "";
                    newAthlete.prenom = keycloak.tokenParsed.given_name || "";
                    
                    setAuthToken(keycloak.token);
                    
                    const athlete: Athlete = await postAthlete(newAthlete);
                    setUser(athlete);
                } catch (error) {
                    console.error("Error :", error);
                }
            }
        };

        syncAndLoadUser();
    }, [keycloak.authenticated, keycloak.token, setUser]);
    */

    async function loginUser(){
        if(keycloak.authenticated){
            setAuthToken(keycloak.token);
            //alert("Connexion en cours : " + keycloak.tokenParsed?.sub + " " + keycloak.tokenParsed?.realm_access?.roles);
            
            const logedUser = await loginOrRegister(keycloak);
            console.log(logedUser);
            if(logedUser!==null){
                setUser(logedUser);
               // alert("Connexion avec succès ! " + keycloak.tokenParsed?.sub);
            }
            else{
                alert("Erreur de connexion " + keycloak.tokenParsed?.sub + " " + keycloak.tokenParsed?.realm_access?.roles);
            }
        }
    }

    useEffect(() => {
        loginUser()
    },[keycloak.authenticated])

    async function handleLogin() {
        await keycloak.login();
    }

    function handleLogout(): void {
        keycloak.logout()
        setUser(new User());
        clearAuthToken();
    }
    return(
        <div>
            <div>
                Etat : {keycloak.authenticated ? 'connecté' : 'non connecté'}
            </div>
            {keycloak.authenticated &&
            <div>
                <div>
                    Keycloak ID : { keycloak.tokenParsed?.sub}
                </div>
                 <div>
                    Prenom : { user.prenom}
                </div>
                <div>
                    Nom : { user.nom}
                </div>
                {user instanceof Athlete && <div>Role : Athlete</div>}
                {user instanceof Coach && <div>Role : Coach</div>}
                {user instanceof Admin && <div>Role : Admin</div>}
            
            </div>
            }
            <button onClick={() => handleLogin()}>
                Se connecter
            </button>
            <button onClick={() => handleLogout()}>
                Se déconnecter
            </button>
        </div>
    )
}

export default Login
