import React, {useEffect, useState} from "react"
import useAxiosTools from "../hooks/AxiosTools"
import {timeTracker} from "../utilities/types"
import {EditSVG, PlaySVG} from "../components/SVG"
import useTracker from "../hooks/TraskerHook"
import {Modal} from "../components/Modals"
import TimeTrackerEdit from "../components/TimeTrackers/TimeTrackerEdit"
import {Link} from "react-router-dom"

const TimeTrackersIndex = () => {

    const {loading, setLoading, errorCatch, errorLabel, axiosGet} = 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 odd:bg-blue-950">
                <span className="w-24 text-center">{tracker.start_at ? (new Date(tracker.start_at)).toSmallFrDate() : ''}</span>
                <span className="w-24 text-center">{(new Date(tracker.end_at)).toSmallFrDate()}</span>
                <Link to={"/todos/" + tracker.to_do?.id} className={`flex-1 ${tracker.to_do?.checked ? 'line-through' : ''}`}>{tracker.to_do.name}</Link>
                <span className="flex gap-2">
                    {!tracker?.to_do?.checked && <button className="flex  w-7 cursor-pointer items-center justify-center"
                            type="button"
                            title="Commencer"
                            onClick={() => startTrackToDo(tracker.to_do)}>
                        <PlaySVG className="w-4"/>
                    </button>}
                    <button onClick={() => setShowTrackers(tracker)}>
                        <EditSVG className="w-5"/>
                    </button>
                </span>
            </li>)}
        </ul>

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

export default TimeTrackersIndex
