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,
    setCurrentTimeTracker: (timeTracker: timeTracker) => void,
    startTrackToDo: (toDo: toDo) => void,
    stopCurrentTimeTrack: () => void,
}

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

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

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

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

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

    return <TrackerContext.Provider value={{currentTimeTracker, setCurrentTimeTracker, startTrackToDo, stopCurrentTimeTrack}}>
        {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
