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

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

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

    const navigate = useNavigate();

    const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        const firstName = nameRef.current?.value || '';
        const lastName = surnameRef.current?.value || '';
        const email = emailRef.current?.value || '';
        const password = passwordRef.current?.value || '';
        const username = firstName + lastName || '';

        try{
            const responseData = await registerUser({username, firstName, lastName, email, password});
            console.log(responseData); //проверка вывода данных
            if (responseData && !responseData.error) {
                console.log('Регистрация успешна')
                navigate('/my-surveys');
            }
            else {
                console.error(`Ошибка регистрации: ${responseData}`);
                console.log('Регистраиця не удалась');
            }
        }
        catch (err) {
            console.error(`Ошибка при отправке запроса ${err}`);
        }
    }

    return (
        <div className={styles.registerContainer}>
            <h2 className={styles.title}>Регистрация</h2>
            <form className={styles.form} onSubmit={handleSubmit}>
                <input
                    className={`${styles.input} ${styles.name}`}
                    type={'text'}
                    placeholder='Имя'
                    ref={nameRef}
                    onFocus={() => setFocused({ ...focused, firstName: true })}
                    onBlur={() => setFocused({ ...focused, firstName: false })}
                    style={{ color: focused.firstName ? 'black' : 'inherit' }}
                />
                <input
                    className={`${styles.input} ${styles.surname}`}
                    type={'text'}
                    placeholder='Фамилия'
                    ref={surnameRef}
                    onFocus={() => setFocused({ ...focused, lastName: true })}
                    onBlur={() => setFocused({ ...focused, lastName: false })}
                    style={{ color: focused.lastName ? 'black' : 'inherit' }}
                />
                <input
                    className={`${styles.input} ${styles.email}`}
                    type={'email'}
                    placeholder='Почта'
                    ref={emailRef}
                    onFocus={() => setFocused({ ...focused, email: true })}
                    onBlur={() => setFocused({ ...focused, email: false })}
                    style={{ color: focused.email ? 'black' : 'inherit' }}
                />
                <input
                    className={`${styles.input} ${styles.password}`}
                    type='password'
                    placeholder='Пароль'
                    ref={passwordRef}
                    onFocus={() => setFocused({ ...focused, password: true })}
                    onBlur={() => setFocused({ ...focused, password: false })}
                    style={{ color: focused.password ? 'black' : 'inherit' }}
                />
                <button className={styles.signUp} type='submit'>Зарегистрироваться</button>
            </form>
            <p className={styles.recommendation}>Уже с нами?
                <Link className={styles.recommendationLink} to='/login'>Войдите!</Link>
            </p>
        </div>
    );
}

export default RegisterForm;
