import React, {createContext, PropsWithChildren, useContext, useEffect, useState} from "react";
import {timeTracker, toDo} from "../utilities/types";
import useAxiosTools from "./AxiosTools";


const TrackerContext = createContext<TrackerProps|undefined>(undefined)

interface TrackerProps {
    currentTimeTracker: timeTracker|null,
    startTrackToDo: (toDo: toDo) => void,
    stopCurrentTimeTrack: () => void,
    isToDoTracked: (toDo: toDo) => boolean,
}

export const TrackerProvider = ({children}: PropsWithChildren) => {
    const [currentTimeTracker, setCurrentTimeTracker] = useState(null)
    const [toDoTracked, setToDoTracked] = useState<toDo|null>(null)
    const {axiosGet, axiosPost, axiosDelete} = useAxiosTools()

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

    const fetchCurrentTimeTracker = async () => {
        try {
            const res = await axiosGet(`/api/time-tracker/user`)
            setCurrentTimeTracker(res.data)
        } catch (error) {
            console.error(error)
        }
    }

    const startTrackToDo = async (toDo: toDo) => {
        try {
            const res = await axiosPost('/api/time-tracker', {todo_id: toDo.id})
            setCurrentTimeTracker(res.data)
        } catch (error) {
            console.error(error)
        }
    }

    const stopCurrentTimeTrack = async () => {
        try {
            const res = await axiosDelete(`/api/time-tracker/user`)
            setCurrentTimeTracker(null)
        } catch (error) {
            console.error(error)
        }
    }

    const isToDoTracked = (toDo: toDo) => toDo.id === toDoTracked?.id

    return <TrackerContext.Provider value={{currentTimeTracker, startTrackToDo, stopCurrentTimeTrack, isToDoTracked}}>
        {children}
    </TrackerContext.Provider>
}

const useTracker = () => {
    const context = useContext(TrackerContext)
    if (context === undefined) {
        throw new Error('Add TrackerProvider to use AuthUserContext')
    }
    return context
}

export default useTracker
