import { useState, useContext, FormEvent } from "react";
import styles from "./LoginForm.module.css";
import Button from "../../../../components/ui/Button/Button";
import Input from "../../../../components/ui/Input/Input";
import Modal from "../../../../components/ui/Modal/Modal";
import { useNavigate } from "react-router";
import { AuthContext, AuthContextType } from "../../../../contexts/Auth/AuthContext";

interface LoginFormProps {
    className?: string;
}

function LoginForm({ className }: LoginFormProps) {
    const navigate = useNavigate();
    const authContext = useContext(AuthContext) as AuthContextType;
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [open, setOpen] = useState(false);

    const { login } = authContext;

    async function handleSubmit(e?: FormEvent) {
        if (e) e.preventDefault();
        const res = await login(email, password);
        if (res.status === 401 || res.status === 422) setOpen(true);
        else navigate("/");
    }

    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter') {
            handleSubmit();
        }
    };



    return (
        <div className={`${className} glassCard ${styles.inputContainer}`} onKeyDown={handleKeyDown}>
            <form onSubmit={handleSubmit}>
                <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}
                        value={password}
                        placeholder="Mot de passe"
                        onChange={e => setPassword(e.target.value)}
                    />
                </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>
            </form>

            <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;
