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

const ToDoStore: FC<ToDoStoreProps> = ({setReload}) => {

    const [toDo, setToDo] = useState('')
    const {errorCatch, errorLabel, axiosPost} = useAxiosTools()

    const onSubmit = async (event: FormEvent) => {
        event.preventDefault()
        try {
            await axiosPost('api/todos', {name: toDo})
            setToDo('')
            setReload(new Date())
        } catch (error) {
            errorCatch(error)
        }
    }

    return <>
        {errorLabel()}
        <form className="flex" onSubmit={onSubmit}>
            <Field name="name"
                   value={toDo}
                   classNameForm="flex-1"
                   className="!mt-0 h-10 rounded-r-none px-2"
                   onChange={event => setToDo(event.target.value)} />
            <button type="submit"
                    className="h-10 rounded-r bg-blue-900 px-5">
                Ajouter
            </button>
        </form>
    </>
}

export default ToDoStore

interface ToDoStoreProps {
    setReload: (date: Date) => void,
}
