import React, {Dispatch, FC, FormEvent, SetStateAction, useState} from "react"
import useAxiosTools from "../../hooks/AxiosTools";
import Field from "../Field";

const AddRainfall: FC<AddRainfallProps> = ({reload}) => {

    const {axiosPost} = useAxiosTools()
    const [date, setDate] = useState((new Date()).toSQLDate())
    const [value, setValue] = useState(0)

    const handleSubmit = async (event: FormEvent) => {
        event.preventDefault()
        try {
            await axiosPost('/api/rainfalls', {date, value})
            setDate((new Date()).toSQLDate())
            setValue(0)
            reload(new Date())
        } catch (e) {
            console.error(e)
        }
    }

    return <form onSubmit={handleSubmit}>
        <h2>Ajout d'une mesure</h2>
        <Field type="date"
               name="date"
               placeholder="Email"
               value={date}
               onChange={event => setDate(event.target.value)}
               autoFocus>Date</Field>
        <Field type="number"
               name="value"
               placeholder="10"
               value={value}
               onChange={event => setValue(Number(event.target.value))}>Mesure</Field>

        <button type="submit" className="mt-3 w-full bg-blue-700 rounded">Valider</button>
    </form>
}

export default AddRainfall

interface AddRainfallProps {
    reload: Dispatch<SetStateAction<Date>>
}
