import React, {useState} from "react"
import {Redirect, Link} from "react-router-dom"
import axios from "axios"
import {Button} from "../components/Button"
import {SERVER_HOST} from "../config/global_constants"


export const Login = props =>
{
    const [email, setEmail] = useState(props.email)
    const [password, setPassword] = useState(props.password)
    const [isLoggedIn, setIsLoggedIn] = useState(props.isLoggedIn)


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


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


    const handleSubmit = e =>
    {
        axios.post(`${SERVER_HOST}/users/login/${email}/${password}`)
        .then(res =>
        {
            localStorage.name = res.data.name
            localStorage.accessLevel = res.data.accessLevel
            localStorage.token = res.data.token

            setIsLoggedIn(true)
        })
        .catch(err => console.log(`${err.response.data}\n${err}`))
    }


    return (
    <form className="form-container" noValidate = {true} id = "loginOrRegistrationForm">
        <h2>Login</h2>
    
        {isLoggedIn ? <Redirect to="/DisplayAllCars"/> : null} 
    
        <input 
            type = "email" 
            name = "email" 
            placeholder = "Email"
            autoComplete="email"
            value={email} 
            onChange={handleEmailChange}
            /><br/>
    
        <input 
            type = "password" 
            name = "password" 
            placeholder = "Password"
            autoComplete="password"
            value={password} 
            onChange={handlePasswordChange}
            /><br/><br/>
    
        <Button value="Login" className="green-button" onClick={handleSubmit}/> 
        <Link className="red-button" to={"/DisplayAllCars"}>Cancel</Link>                                      
    </form>
    )
}