import { useEffect, useRef, useState } from 'react'
import { GetDeviceLiveStats } from '@/wailsjs/go/main/App'
import type { device } from '@/wailsjs/go/models'

export type DeviceLiveStats = device.DeviceLiveStats

export function useDeviceLiveStats(deviceId: string | null) {
  const [stats, setStats] = useState<DeviceLiveStats | null>(null)
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)

  useEffect(() => {
    if (!deviceId) {
      setStats(null)
      return
    }

    // Fetch immediately, then every second
    GetDeviceLiveStats(deviceId).then(setStats).catch(() => {})

    intervalRef.current = setInterval(() => {
      GetDeviceLiveStats(deviceId).then(setStats).catch(() => {})
    }, 1000)

    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current)
    }
  }, [deviceId])

  return stats
}
