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

const TimeTrackerEdit: FC<TimeTrackerEditProps> = ({timeTracker, setReload}) => {

    const {errorCatch, errorLabel, axiosPut} = useAxiosTools()
    const [trackerForm, setTrackerForm] = useState<timeTracker>(timeTracker)

    const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setTrackerForm({...trackerForm, [event.target.name]: event.target.value.replace('T', ' ')})
    }

    const onSubmit = async (event: FormEvent) => {
        console.log('submit', trackerForm, event)
        try {
            const res = await axiosPut(`/api/time-trackers/${timeTracker.id}`, trackerForm)
            setReload(res.data)
        } catch (error) {
            errorCatch(error)
        }
    }

    return <form onSubmit={onSubmit} className="px-5 py-3">
        {errorLabel()}
        <h2 className="mb-3 text-lg font-bold">Modification de l&apos;entrée</h2>
        <Field name="start_at"
               type="datetime-local"
               className="mb-2"
               value={trackerForm.start_at}
               onChange={handleChange}>
            Début
        </Field>
        {timeTracker.end_at && <Field name="end_at"
               type="datetime-local"
               value={trackerForm.end_at}
               onChange={handleChange}>
            Fin
        </Field>}

        <button type="submit" className="btn-primary mt-5 w-full" onClick={onSubmit}>Valider</button>
    </form>
}

export default TimeTrackerEdit

interface TimeTrackerEditProps {
    timeTracker: timeTracker,
    setReload: (elem: timeTracker) => void,
}
