"use client"

import { useEffect, useState } from "react"

/**
 * 仪表盘实时更新 Hook（L6）。
 *
 * 基于 Server-Sent Events (SSE) 实现轻量级实时更新，
 * 避免引入 WebSocket 的复杂依赖。
 *
 * - 自动重连（指数退避，最大 30s）
 * - 组件卸载时自动清理 EventSource
 * - 连接状态可查询（connecting/connected/error）
 *
 * @param url SSE 端点 URL
 * @param eventName 监听的事件名（默认 "update"）
 */
export type ConnectionStatus = "connecting" | "connected" | "error" | "closed"

export function useDashboardRealtime<T = unknown>(
  url: string | null,
  eventName = "update",
): {
  status: ConnectionStatus
  lastMessage: T | null
  lastUpdatedAt: Date | null
} {
  const [status, setStatus] = useState<ConnectionStatus>("connecting")
  const [lastMessage, setLastMessage] = useState<T | null>(null)
  const [lastUpdatedAt, setLastUpdatedAt] = useState<Date | null>(null)

  useEffect(() => {
    if (!url) {
      setStatus("closed")
      return
    }

    let eventSource: EventSource | null = null
    let retryCount = 0
    let retryTimer: ReturnType<typeof setTimeout> | null = null

    const connect = () => {
      setStatus("connecting")
      eventSource = new EventSource(url)

      eventSource.onopen = () => {
        retryCount = 0
        setStatus("connected")
      }

      eventSource.addEventListener(eventName, (event) => {
        try {
          const data = JSON.parse(event.data) as T
          setLastMessage(data)
          setLastUpdatedAt(new Date())
        } catch {
          // 忽略解析失败的消息
        }
      })

      eventSource.onerror = () => {
        setStatus("error")
        eventSource?.close()
        // 指数退避重连，最大 30s
        const delay = Math.min(1000 * Math.pow(2, retryCount), 30000)
        retryCount++
        retryTimer = setTimeout(connect, delay)
      }
    }

    connect()

    return () => {
      eventSource?.close()
      if (retryTimer) clearTimeout(retryTimer)
    }
  }, [url, eventName])

  return { status, lastMessage, lastUpdatedAt }
}
