import {useState, useContext, useEffect} from "react";
import styles from "./loginForm.module.css";
import Button from "../../../../components/ui/button/button.tsx";
import Input from "../../../../components/ui/input/input.tsx";
import Modal from "../../../../components/ui/modal/modal.tsx";
import { useNavigate } from "react-router";
import { AuthContext } from "../../../../contexts/auth/AuthContext.js";


function LoginForm({ className }) {


    const navigate = useNavigate();
    const { login } = useContext(AuthContext);
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [open , setOpen] = useState(false);


    const handleSubmit = async () => {
        const res = await login(email, password);
        if (res.status === 401 || res.status === 422) setOpen(true);
        else navigate("/");
    };

    useEffect(() => {
        const listener = (e) => {
            if (e.key === "Enter") {
                handleSubmit();
            }
        };
        window.addEventListener("keydown", listener);

        return () => {
            window.removeEventListener("keydown", listener);
        };
    },);

    return (
        <div className={`${className} glassCard ${styles.inputContainer}`}>
            <div className={styles.formgroup}>
                <Input
                    type="email"
                    value={email}
                    placeholder="Adresse mail"
                    onChange={e => setEmail(e.target.value)}
                    style={{ width: '100%' }}
                />
            </div>
            <div className={styles.formgroup}>
                <Input password={true} onChange={e => setPassword(e.target.value)} value={password} placeholder={"Mot de passe"} />
            </div>

            <div className={styles.logButton}>
                <Button variant={"transparent"} onClick={() => navigate("/register")}>Vous n'avez pas de compte ?</Button>
                <Button onClick={handleSubmit} variant={"default"}> Se connecter </Button>
            </div>

            <Modal title={"Impossible de se connecter"} open={open} onClose={() => setOpen(false)}>
                <p>L'Email ou le mot de passe est incorrect</p>
            </Modal>
        </div>
    );
}

export default LoginForm;

