import { useKeycloak } from '@react-keycloak/web'
import { useEffect, useState } 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';
import { Modal } from './Modal';
import './style/topBar.css';

export const Login =() =>{
    const {userLocal: user,setUserLocal: setUser} = useLocalData()
    const { keycloak } = useKeycloak();
    const [open,setOpen] = useState<boolean>(false);


    async function loginUser(){
        if(keycloak.authenticated){
            setAuthToken(keycloak.token);
            
            const logedUser = await loginOrRegister(keycloak);
            console.log(logedUser);
            if(logedUser!==null){
                setUser(logedUser);
            }
            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();
        setOpen(false);
    }

    function handleOpen(): void {
        setOpen(!open);
    }

    if(keycloak.authenticated){
    return(
            <div className='loginContainer'>
                <button className="loginButton" onClick={()=>handleOpen()}>{user.prenom}</button>
                {open &&
                <div className='login'>
                    <div>
                        <div>
                            Prenom : { user.prenom}
                        </div>
                        <div>
                            Nom : { user.nom}
                        </div>
                        {/* <div>Keycloak ID : { keycloak.tokenParsed?.sub}</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={() => handleLogout()}>
                        Se déconnecter
                    </button>
                </div>
                }
            </div>
        )
    }
    else{
        return(
            <div>
                <button onClick={() => handleLogin()}>
                    Se connecter
                </button>
            </div>
        )
    }
    
}

export default Login
