"use client"

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

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

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

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

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

    // Initial fetch
    fetchDepartmentUpdates()

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

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

  return { isConnected, refetch: fetchDepartmentUpdates }
}
