"use client"

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

interface TeamUpdateData {
  stats?: any
  users?: any[]
  field?: string
  department?: string
  team?: string
}

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

  const fetchTeamUpdates = async () => {
    try {
      // Fetch team data in parallel
      const [statsRes, usersRes] = await Promise.all([
        fetch("/api/admin/team-stats", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ adminId }),
        }),
        fetch("/api/admin/team-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,
        department: usersData.department,
        team: usersData.team,
      }
      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 team updates:", err)
      setIsConnected(false)
    }
  }

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

    // Initial fetch
    fetchTeamUpdates()

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

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

  return { isConnected, refetch: fetchTeamUpdates }
}
