'use client'

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

interface PresenceUser {
  userId: string
  name: string
  connectedAt: string
}

interface PresenceIndicatorProps {
  documentId: string
  currentUserId?: string
}

const COLORS = ['#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6', '#ec4899']

export function PresenceIndicator({ documentId, currentUserId }: PresenceIndicatorProps) {
  const [users, setUsers] = useState<PresenceUser[]>([])
  const eventSourceRef = useRef<EventSource | null>(null)
  const heartbeatRef = useRef<ReturnType<typeof setInterval>>(undefined)

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

    const es = new EventSource(`/api/cms/presence/${documentId}`)
    eventSourceRef.current = es

    es.addEventListener('presence', (event) => {
      try {
        const data = JSON.parse(event.data) as PresenceUser[]
        setUsers(data.filter((u) => u.userId !== currentUserId))
      } catch {}
    })

    es.onerror = () => {
      es.close()
    }

    heartbeatRef.current = setInterval(() => {
      fetch(`/api/cms/presence/${documentId}/heartbeat`, {
        method: 'POST',
        credentials: 'include',
      }).catch(() => {})
    }, 30_000)

    return () => {
      es.close()
      if (heartbeatRef.current) clearInterval(heartbeatRef.current)
    }
  }, [documentId, currentUserId])

  if (users.length === 0) return null

  return (
    <div className="flex items-center gap-1" title={`${users.length} other editor(s) active`}>
      {users.slice(0, 5).map((user, i) => (
        <div
          key={user.userId}
          className="flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium text-white ring-2 ring-white"
          style={{ backgroundColor: COLORS[i % COLORS.length] }}
          title={user.name}
        >
          {user.name.charAt(0).toUpperCase()}
        </div>
      ))}
      {users.length > 5 && (
        <div className="bg-muted text-muted-foreground flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium ring-2 ring-white">
          +{users.length - 5}
        </div>
      )}
    </div>
  )
}
