"use client"

import { useEffect, useState, useRef } from "react"

interface UpdateData {
  stats?: any
  users?: any[]
  lastReset?: any
}

export function useRealTimeUpdates(onUpdate?: (data: UpdateData) => void) {
  const [isConnected, setIsConnected] = useState(false)
  const intervalRef = useRef<NodeJS.Timeout>()
  const lastDataRef = useRef<string>("")

  const fetchUpdates = async () => {
    try {
      // Fetch all data in parallel
      const [statsRes, usersRes, resetRes] = await Promise.all([
        fetch("/api/admin/stats"),
        fetch("/api/admin/users"),
        fetch("/api/admin/last-reset"),
      ])

      const [stats, users, lastReset] = await Promise.all([statsRes.json(), usersRes.json(), resetRes.json()])

      const newData = { stats, users, lastReset }
      const newDataString = JSON.stringify(newData)

      // Only trigger update if data actually changed
      if (newDataString !== lastDataRef.current) {
        lastDataRef.current = newDataString
        if (onUpdate) {
          onUpdate(newData)
        }
      }

      setIsConnected(true)
    } catch (err) {
      console.error("Error fetching updates:", err)
      setIsConnected(false)
    }
  }

  useEffect(() => {
    // Initial fetch
    fetchUpdates()

    // Set up polling every 2 seconds
    intervalRef.current = setInterval(fetchUpdates, 2000)

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

  return { isConnected, refetch: fetchUpdates }
}
