"use client"

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

interface FieldUpdateData {
  stats?: any
  users?: any[]
  field?: string
}

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

  const fetchFieldUpdates = async () => {
    try {
      // Fetch field data in parallel
      const [statsRes, usersRes] = await Promise.all([
        fetch("/api/admin/field-stats", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ adminId }),
        }),
        fetch("/api/admin/field-users", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ adminId }),
        }),
      ])

      const [statsData, usersData] = await Promise.all([statsRes.json(), usersRes.json()])

      const newData = {
        stats: statsData,
        users: usersData.users,
        field: usersData.field,
      }
      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 field updates:", err)
      setIsConnected(false)
    }
  }

  useEffect(() => {
    if (!adminId) return

    // Initial fetch
    fetchFieldUpdates()

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

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

  return { isConnected, refetch: fetchFieldUpdates }
}
