import React, {useEffect, useState} from "react"
import useTracker from "../../hooks/TraskerHook"
import {Link} from "react-router-dom"
import {StopSVG} from "../SVG"
import TimeTrackerEdit from "./TimeTrackerEdit"
import {Modal} from "../Modals"
import {timeTracker} from "../../utilities/types"

const Tracker = () => {

    const [timer, setTimer] = useState('')
    const {currentTimeTracker, setCurrentTimeTracker, stopCurrentTimeTrack} = useTracker()
    const [showTrackers, setShowTrackers] = useState<timeTracker|null>(null)
    const [reload, setReload] = useState<timeTracker|null>(null)

    useEffect(() => {
        setTimer(formatTimer(currentTimeTracker?.start_at))
    }, [currentTimeTracker])

    useEffect(() => {
        setTimeout(() => setTimer(formatTimer(currentTimeTracker?.start_at)), 1000)
    }, [timer])

    useEffect(() => {
        if (reload) {
            setCurrentTimeTracker(reload)
            setShowTrackers(null)
        }
    }, [reload])

    const formatTimer = (startAt: string|null|undefined) => {
        if (!startAt) {
            return '--:--'
        }
        const timer = Math.floor(((new Date()).getTime() - (new Date(startAt)).getTime()) / 1000)
        return Number(timer).durationify()
    }

    return <div>
        {currentTimeTracker
            ? <div className="flex gap-2">
                <Link to={`/todos/${currentTimeTracker?.to_do?.id}`} className="font-bold">
                    {currentTimeTracker?.to_do?.name}
                </Link>
                <button type="button" onClick={() => setShowTrackers(currentTimeTracker)}>{timer}</button>
                <button onClick={stopCurrentTimeTrack} className="flex items-center">
                    <StopSVG className="w-6" />
                </button>
            </div>
            : <div>--:--</div>
        }

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

export default Tracker
