import React, {useEffect, useRef, useState} from 'react';
import {connect} from 'react-redux';
import {NavLink, useHistory} from 'react-router-dom';
import {actionLogin} from '../../Actions/action_login';
import LoginError from '../../Components/LoginError/LoginError';
import './Login.css';

const Login = ({onLogin = null, checkLogin = false, promiseLoginStatus, payloadLogin, loginNetworkError}) => {      //деструктуризация объекта

    let history = useHistory();

    if (checkLogin) {
        history.push('/profile')
    }

    if (localStorage.authToken) {
        history.push('/profile')
    }
    if (loginNetworkError) {
        history.push('/404')
    }

    // useEffect(()=>{
    //     if(checkLogin) {
    //         history.push('/profile')
    //     }
    // }, [checkLogin])

    const loginRef = useRef(null)
    const pasRef = useRef(null)

    const [login, setLogin] = useState("")
    const [password, setPassword] = useState("")

    return (
        <div className='login-wrapper'>
            <input
                value={login}
                placeholder="Login"
                ref={loginRef}
                onChange={(e) => setLogin(e.target.value)}
            />
            {/* зачем нужен value? */}
            {/* <input placeholder="Login" ref={loginRef} onChange={(e) => setLogin(e.target.value)}></input> */}
            <input
                value={password}
                placeholder="Password"
                ref={pasRef} onChange={(e) => setPassword(e.target.value)} type="password"
            />

            <button onClick={() => onLogin(login, password)}>
                <b>Login</b>
            </button>

            <nav>
                <NavLink to="/registration">Registration</NavLink>
            </nav>

            {promiseLoginStatus === 'RESOLVED' && payloadLogin === null && <LoginError/>}
        </div>
    )
}

const CLogin = connect((state) => ({
    checkLogin: state.auth.isLogin,
    promiseLoginStatus: state?.promise?.Login?.status,
    payloadLogin: state?.promise?.Login?.payload?.data?.login,
    loginNetworkError: state?.networkError?.loginNetworkError
}), {onLogin: actionLogin})(Login)

export default CLogin;