import React, {useState} from "react"


export const LoginForm = props =>
{
    const [email, setEmail] = useState("")
    const [password, setPassword] = useState("")
    const [wasSubmittedAtLeastOnce, setWasSubmittedAtLeastOnce] = useState(false)


    const handleEmailChange = e =>
    {
        setEmail(e.target.value)
    }


    const handlePasswordChange = e =>
    {
        setPassword(e.target.value)
    }


    const handleSubmit = e =>
    {
        setWasSubmittedAtLeastOnce(true)
        const formInputsState = validate()

        if(Object.keys(formInputsState).every(index => formInputsState[index]))
        {
            alert(`Registered details to be submitted are...    email: ${email} password: ${password}`)
        }
        else // invalid inputs in form
        {
            e.preventDefault()
            return
        }
    }


    const validateEmail = () =>
    {
        // valid email pattern
        const pattern = /^[^@]+@[^@]+\.[a-zA-Z]{2,6}$/
        return pattern.test(String(email).toLowerCase())
    }


    const validatePassword = () =>
    {
        const pattern = /^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[£!#€$%^&*]).{10,}$/
        return pattern.test(String(password))
    }


    const validate = () =>
    {
        return {
            email: validateEmail(),
            password: validatePassword()
        }
    }


    let errorMessage = ""
    if(wasSubmittedAtLeastOnce)
    {
        errorMessage = <div className="error">Login Details are incorrect<br/></div>
    }

    return (
    <form noValidate = {true} id = "loginForm" onSubmit = {handleSubmit}>
        {errorMessage}
    
        <input  
            name = "email"              
            type = "email"
            placeholder = "Email"
            value = {email}
            onChange = {handleEmailChange}
            />
    
    
        <input   
            name = "password"          
            type = "password"
            placeholder = "Password"
            value = {password}
            onChange = {handlePasswordChange}
            />
    
    
        <input 
            type = "submit" 
            value = "Login" 
            />
    </form>
    )
}