"use client"

import { useEffect, useState } from "react"

interface SSEMessage {
  type: string
  data?: any
  timestamp?: string
}

export function useServerSentEvents(onMessage?: (message: SSEMessage) => void) {
  const [isConnected, setIsConnected] = useState(false)
  const [lastMessage, setLastMessage] = useState<SSEMessage | null>(null)

  useEffect(() => {
    const eventSource = new EventSource("/api/admin/events")

    eventSource.onopen = () => {
      console.log("SSE connected to shelter.ruff.co.il")
      setIsConnected(true)
    }

    eventSource.onmessage = (event) => {
      try {
        const message: SSEMessage = JSON.parse(event.data)
        setLastMessage(message)
        if (onMessage && message.type !== "ping") {
          onMessage(message)
        }
      } catch (err) {
        console.error("Error parsing SSE message:", err)
      }
    }

    eventSource.onerror = () => {
      console.log("SSE connection error")
      setIsConnected(false)
    }

    return () => {
      eventSource.close()
    }
  }, [onMessage])

  return { isConnected, lastMessage }
}
