"use client"

import { useEffect, useState } from "react"

import { Badge } from "@/shared/components/ui/badge"

import { getUnreadMessageCountAction } from "../actions"

/**
 * 未读消息计数徽章
 *
 * 在侧边栏 Messages 导航项旁显示未读私信数。
 *
 * P1-5: 优先订阅 SSE 端点（/api/notifications/stream）获取实时更新，
 * payload.unreadMessageCount 字段即为未读私信数。
 * SSE 不可用时自动降级为 30 秒轮询。
 */
const POLL_INTERVAL_MS = 30_000
const SSE_URL = "/api/notifications/stream"

export function UnreadMessageBadge() {
  const [count, setCount] = useState(0)

  useEffect(() => {
    let active = true
    let es: EventSource | null = null
    let pollTimer: ReturnType<typeof setInterval> | null = null
    let usingSSE = false

    const fetchCount = async (): Promise<void> => {
      if (!active) return
      const res = await getUnreadMessageCountAction()
      if (!active) return
      if (res.success && typeof res.data === "number") {
        setCount(res.data)
      }
    }

    const startPolling = (): void => {
      if (pollTimer) return
      void fetchCount()
      pollTimer = setInterval(() => {
        void fetchCount()
      }, POLL_INTERVAL_MS)
    }

    const stopPolling = (): void => {
      if (pollTimer) {
        clearInterval(pollTimer)
        pollTimer = null
      }
    }

    // 尝试建立 SSE 连接
    try {
      es = new EventSource(SSE_URL)
      usingSSE = true

      es.onmessage = (event): void => {
        if (!active) return
        try {
          const payload = JSON.parse(event.data) as {
            type: "update" | "error" | string
            unreadMessageCount?: number
          }
          if (payload.type === "update" && typeof payload.unreadMessageCount === "number") {
            setCount(payload.unreadMessageCount)
          }
        } catch {
          // 忽略解析错误
        }
      }

      // SSE 连接失败时降级为轮询
      es.onerror = (): void => {
        if (!active) return
        usingSSE = false
        if (es) {
          es.close()
          es = null
        }
        startPolling()
      }
    } catch {
      // EventSource 不可用，降级为轮询
      usingSSE = false
      startPolling()
    }

    // 兜底：如果 SSE 在 5 秒内未收到任何数据，启动轮询作为保险
    const fallbackTimer = setTimeout(() => {
      if (active && usingSSE && count === 0) {
        // SSE 可能未推送初始数据，拉取一次
        void fetchCount()
      }
    }, 5_000)

    return () => {
      active = false
      if (es) es.close()
      stopPolling()
      clearTimeout(fallbackTimer)
    }
  }, [])

  if (count <= 0) return null

  return (
    <Badge
      variant="destructive"
      className="ml-auto flex h-5 min-w-5 items-center justify-center px-1.5 text-[10px]"
      aria-label={`${count} unread messages`}
    >
      {count > 99 ? "99+" : count}
    </Badge>
  )
}
