import React, {useEffect, useState} from "react"
import useAxiosTools from "../hooks/AxiosTools";
import {timeTracker, toDo} from "../utilities/types";
import {PlaySVG} from "../components/SVG";
import useTracker from "../hooks/TraskerHook";
import {Modal} from "../components/Modals";
import TimeTrackerEdit from "../components/TimeTrackers/TimeTrackerEdit";

const TimeTrackersIndex = () => {

    const {loading, setLoading, errorCatch, errorLabel, axiosGet, axiosPut} = useAxiosTools(true)
    const [timeTrackers, setTimeTrackers] = useState<timeTracker[]>([])
    const [showTrackers, setShowTrackers] = useState<timeTracker|null>(null)
    const {startTrackToDo} = useTracker()

    useEffect(() => {
        fetchTimeTrackers()
    }, [])

    const fetchTimeTrackers = async () => {
        try {
            const res = await axiosGet('api/time-trackers')
            setTimeTrackers(res.data)
        } catch (error) {
            errorCatch(error)
        } finally {
            setLoading(false)
        }
    }

    return <div className="p-5">
        {errorLabel()}
        <ul>
            {timeTrackers.map(tracker => <li key={tracker.id} className="flex justify-between gap-5">
                <span className="text-center w-36">{tracker.start_at ? (new Date(tracker.start_at)).toSmallFrDate() : ''}</span>
                <span className="text-center w-36">{(new Date(tracker.end_at)).toSmallFrDate()}</span>
                <span className={`flex-1 ${tracker.to_do.checked ? 'line-through' : ''}`}>{tracker.to_do.name}</span>
                <span className="flex gap-2">
                    {!tracker.to_do.checked && <button className="cursor-pointer  w-7 justify-center flex items-center"
                            type="button"
                            title="Commencer"
                            onClick={() => startTrackToDo(tracker.to_do)}>
                        <PlaySVG className="w-4"/>
                    </button>}
                    <button onClick={() => setShowTrackers(tracker)}>
                        Edit
                    </button>
                </span>
            </li>)}
        </ul>

        <Modal show={!!showTrackers} closeModal={() => setShowTrackers(null)}>
            {showTrackers && <TimeTrackerEdit timeTracker={showTrackers} />}
        </Modal>
    </div>
}

export default TimeTrackersIndex
