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 AddCar = props =>
{
    const [model, setModel] = useState("")
    const [colour, setColour] = useState("")
    const [year, setYear] = useState("")
    const [price, setPrice] = useState("")
    const [redirectToDisplayAllCars, setRedirectToDisplayAllCars] = useState(false)


    const handleModelChange = e =>
    {
        setModel(e.target.value)
    }


    const handleColourChange = e =>
    {
        setColour(e.target.value)
    }


    const handleYearChange = e =>
    {
        setYear(e.target.value)
    }


    const handlePriceChange = e =>
    {
        setPrice(e.target.value)
    }


    const handleSubmit = (e) =>
    {
        e.preventDefault()

        const carObject = {
            model: model,
            colour: colour,
            year: year,
            price: price
        }

        axios.post(`${SERVER_HOST}/cars`, carObject)
        .then(res =>
        {
            setRedirectToDisplayAllCars(true)
        })
        .catch(err => console.log(`${err.response.data}\n${err}`))
    }


    return (
    <div className="form-container"> 
        {redirectToDisplayAllCars ? <Redirect to="/DisplayAllCars"/> : null}                                            
    
        <form>
            <label>Model</label>
            <input autoFocus type="text" name="model" value={model} onChange={handleModelChange} />
    
            <label>Colour</label>
            <input type="text" name="colour" value={colour} onChange={handleColourChange} />
    
            <label>Year</label>
            <input type="text" name="year" value={year} onChange={handleYearChange} />
    
            <label>Price</label>
            <input type="text" name="price" value={price} onChange={handlePriceChange} />
    
            <Button value="Add" className="green-button" onClick={handleSubmit}/>            
    
            <Link className="red-button" to={"/DisplayAllCars"}>Cancel</Link>
        </form>
    </div>
    )
}