import React, {useRef, useState} from 'react';
import {NavLink} from 'react-router-dom';
import './Registration.css';
import ExistingLoginError from "../../Components/RegistrationError/ExistingLoginError";
import ConfirmPasswordError from "../../Components/RegistrationError/ConfirmPasswordError";
import {connect} from "react-redux";
import {actionRegistrations} from "../../Actions/action_registration";

const Registration = ({onRegistration}) => {

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

    const [login, setLogin] = useState("")
    const [password, setPassword] = useState("")
    const [confirmPassword, setConfirmPassword] = useState("")
    const [show, setShow] = useState(false)

    const isRegistrationValid = () => {
        if(!login || !password || !confirmPassword) return false
        if(password !== confirmPassword) return false   // indexOf
        else return true
    }

    return (
        <div className='registration-wrapper'>
            <input
                value={login}
                placeholder="Login"
                ref={loginRef}
                onChange={(e) => setLogin(e.target.value)}/>
            <input
                value={password}
                placeholder="Password"
                ref={pasRef}
                onChange={(e) => setPassword(e.target.value)}
                type="password"
            />
            <input
                value={confirmPassword}
                placeholder="Confirm Password"
                ref={confirmPasRef}
                onChange={(e) => setConfirmPassword(e.target.value)}
                type="password"
            />

            <button
                onClick={() => {
                    if(isRegistrationValid()) {
                        onRegistration(login, password)
                    }
                    else {
                        setShow(true)
                    }
                }}
                // disabled={!isRegistrationValid()}
                className={isRegistrationValid() ? 'button-hover': ''}
            >
                <b>Registration</b>
            </button>

            <nav>
                <NavLink to="/login">Login</NavLink>
            </nav>

            <ExistingLoginError/>
            {show && <ConfirmPasswordError/>}
        </div>
    )
}

const CRegistration = connect(null, {
    onRegistration: actionRegistrations
})(Registration)

export default CRegistration