import { useAppSelector } from "@hooks"
import { CategoryType } from "@shared/types/category.type"
import { useEffect, useState } from 'react'

export const useUpdateIndicatorViewModel = (category: CategoryType) => {
    const { thunks } = useAppSelector((state) => state.routine)
    const [secondsSinceUpdate, setSecondsSinceUpdate] = useState<number>(-1)

    useEffect(() => {
        const updateTimer = () => {
            const lastupdate = thunks[category]?.lastupdate
            if (lastupdate) {
                setSecondsSinceUpdate(Math.round((Date.now() - lastupdate) / 1000))
            } else {
                setSecondsSinceUpdate(-1)
            }
        }

        // Initial update
        updateTimer()

        // Set up interval for updates
        const intervalId = setInterval(updateTimer, 1000)

        return () => clearInterval(intervalId)
    }, [category, thunks])

    const getStatusColor = (updateInterval: number) => {
        const updateIntervalSeconds = updateInterval / 1000
        if (secondsSinceUpdate > updateIntervalSeconds * 0.9) return "text-primary"
        if (secondsSinceUpdate > updateIntervalSeconds * 1.3) return "text-danger"
        return "text-bg-primary"
    }

    return {
        secondsSinceUpdate,
        getStatusColor
    }
}