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


export const AddCar = props =>
{

    const [model, setModel] = useState(props.model)
    const [colour, setColour] = useState(props.colour)
    const [year, setYear] = useState(props.year)
    const [price, setPrice] = useState(props.price)
    const [selectedFiles, setSelectedFiles] = useState(null)
    const [redirectToDisplayAllCars, setRedirectToDisplayAllCars] = useState(localStorage.accessLevel < ACCESS_LEVEL_ADMIN)


    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 handleFileChange = e =>
    {
        setSelectedFiles(e.target.files)
    }


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

        let formData = new FormData()

        formData.append("model", model)
        formData.append("colour", colour)
        formData.append("year", year)
        formData.append("price", price)

        if(selectedFiles)
        {
            for(let i = 0;
            i < selectedFiles.length; i++)
            {
                formData.append("carPhotos", selectedFiles[i])
            }
        }

        axios.post(`${SERVER_HOST}/cars`, formData, {headers: {"authorization": localStorage.token, "Content-type": "multipart/form-data"}})
        .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} />
    
            <label>Photos</label>
            <input type = "file" multiple onChange = {handleFileChange} />
    
            <Button value="Add" className="green-button" onClick={handleSubmit}/>            
    
            <Link className="red-button" to={"/DisplayAllCars"}>Cancel</Link>
        </form>
    </div>
    )
}