import React, {useState, useEffect} 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 EditCar = props =>
{
    const [model, setModel] = useState("")
    const [colour, setColour] = useState("")
    const [year, setYear] = useState("")
    const [price, setPrice] = useState("")
    const [redirectToDisplayAllCars, setRedirectToDisplayAllCars] = useState(false)
    const [wasSubmittedAtLeastOnce, setWasSubmittedAtLeastOnce] = useState(false)


    useEffect(() =>
    {
        axios.get(`${SERVER_HOST}/cars/${props.match.params.id}`)
        .then(res =>
        {
            
            setModel(res.data.model)
            setColour(res.data.colour)
            setYear(res.data.year)
            setPrice(res.data.price)
        })
        .catch(err => console.log(`${err.response.data}\n${err}`))
    }, [props.match.params.id])


    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()

        setWasSubmittedAtLeastOnce(true);

        const formInputsState = validate();

        if(Object.keys(formInputsState).every(index => formInputsState[index]))
        {
            const carObject = {
                model: model,
                colour: colour,
                year: year,
                price: price
            }

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


    const validateModel = () =>
    {
        const pattern = /^[A-Za-z]+$/;
        return pattern.test(String(model))
    }


    const validateColour = () =>
    {
        const pattern = /^[A-Za-z]+$/;
        return pattern.test(String(colour))
    }


    const validateYear = () =>
    {
        const yearNumber = parseInt(year)
        const today = new Date()
        return ((yearNumber >= 1990) && (yearNumber <= today.getFullYear()))
    }


    const validatePrice = () =>
    {
        const priceNumber = parseInt(price)
        return ((priceNumber >= 1000) && (priceNumber <= 100000))
    }


    const validate = () =>
    {
        return {
            model: validateModel(),
            colour: validateColour(),
            year: validateYear(),
            price: validatePrice()
        };
    }



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

    return (
    <div className="form-container">
    
        {redirectToDisplayAllCars ? <Redirect to="/DisplayAllCars"/> : null}  
    
        <form>
            {errorMessage}
    
            <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="Update" className="green-button" onClick={handleSubmit}/>  
    
            <Link className="red-button" to={"/DisplayAllCars"}>Cancel</Link>
        </form>
    </div>
    )
}