import {Link, useNavigate} from "react-router-dom";
import styles from './LoginForm.module.css';
import {useRef, useState} from 'react';
import {authUser} from "../../api/AuthApi.ts";

const LoginForm = () => {
    const [focused, setFocused] = useState({
        email: false,
        password: false
    });

    const navigate = useNavigate();
    const [error, setError] = useState<string | null>(null);

    const emailRef = useRef<HTMLInputElement>(null);
    const passwordRef = useRef<HTMLInputElement>(null);

    const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        const email = emailRef.current?.value ?? '';
        const password = passwordRef.current?.value ?? '';
        setError(null);

        try{
            if (email === '' || password === '')
                setError('Заполните все поля')
            else {
                const responseData =  await authUser({email, password});
                if (responseData && !responseData.error)
                    navigate('/my-surveys');
                else
                    setError('Неверный логин или пароль')
            }
        }
        catch(err){
            console.error('Ошибка при отправке запроса:', err);
            setError('Неверный логин или пароль')
        }
    }

    const handleChange = () => {
        if (error) {
            setError(null);
        }
    }

    return (
        <div className={styles.loginContainer}>
            <h2 className={styles.title}>С возвращением!</h2>
            <form className={styles.form} onSubmit={handleSubmit}>
                <input
                    className={`${styles.input} ${styles.email}`}
                    type={'email'}
                    placeholder='Почта'
                    ref={emailRef}
                    onChange={handleChange}
                    onFocus={() => setFocused({ ...focused, email: true })}
                    onBlur={() => setFocused({ ...focused, email: false })}
                    style={{ color: focused.email ? 'black' : 'inherit' }}
                />
                <div className={styles.password_container}>
                    <input
                        className={`${styles.input} ${styles.password} ${error ? styles.error : ''}`}
                        type='password'
                        placeholder='Пароль'
                        ref={passwordRef}
                        onChange={handleChange}
                        onFocus={() => setFocused({ ...focused, password: true })}
                        onBlur={() => setFocused({ ...focused, password: false })}
                        style={{ color: focused.password ? 'black' : 'inherit' }}
                    />
                    {error && <p className={styles.errorMessage}>{error}</p>}
                </div>
                <button className={styles.signIn} type="submit">Войти</button>
            </form>
            <p className={styles.recommendation}>Еще не с нами?
                <Link className={styles.recommendationLink} to='/register'>Зарегистрируйтесь!</Link>
            </p>
        </div>
    );
}

export default LoginForm;
