import { useState } from "react";
import { loginWithAppPassword, getToken, logout } from "../auth";

function TestLogin() {
    const [username, setUsername] = useState("");
    const [appPassword, setAppPassword] = useState("");
    const [token, setToken] = useState(getToken());

    const handleLogin = async (e) => {
        e.preventDefault();
        const newToken = await loginWithAppPassword(username, appPassword);
        if (newToken) {
            setToken(newToken);
            alert("Connexion réussie !");
        } else {
            alert("Échec de la connexion !");
        }
    };

    const handleLogout = () => {
        logout();
        setToken(null);
        alert("Déconnexion réussie !");
    };

    return (
        <div>
            <h2>Connexion</h2>
            {token ? (
                <div>
                    <p>✅ Connecté avec le token : {token}</p>
                    <button onClick={handleLogout}>Déconnexion</button>
                </div>
            ) : (
                <form onSubmit={handleLogin}>
                    <input
                        type="text"
                        placeholder="Nom d'utilisateur"
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                        required
                    />
                    <input
                        type="text"
                        placeholder="Mot de passe d'application"
                        value={appPassword}
                        onChange={(e) => setAppPassword(e.target.value)}
                        required
                    />
                    <button type="submit">Se connecter</button>
                </form>
            )}
        </div>
    );
}

export default TestLogin;