'use client'

import { memo, useState, useEffect } from 'react'
import { Sparkles } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useLanguage } from '@/lib/i18n/LanguageProvider'
import { getConnectionsCount } from '@/lib/connections-cache'

interface ConnectionsBadgeProps {
  noteId: string
  onClick?: () => void
  className?: string
}

export const ConnectionsBadge = memo(function ConnectionsBadge({ noteId, onClick, className }: ConnectionsBadgeProps) {
  const { t } = useLanguage()
  const [connectionCount, setConnectionCount] = useState<number>(0)
  const [isLoading, setIsLoading] = useState(false)
  const [isHovered, setIsHovered] = useState(false)
  const [fetchAttempted, setFetchAttempted] = useState(false)

  useEffect(() => {
    if (fetchAttempted) return
    setFetchAttempted(true)

    let isMounted = true

    const fetchConnections = async () => {
      setIsLoading(true)
      try {
        const count = await getConnectionsCount(noteId)
        if (isMounted) {
          setConnectionCount(count)
        }
      } catch (error) {
        console.error('[ConnectionsBadge] Failed to fetch connections:', error)
        if (isMounted) {
          setConnectionCount(0)
        }
      } finally {
        if (isMounted) {
          setIsLoading(false)
        }
      }
    }

    fetchConnections()

    return () => {
      isMounted = false
    }
  }, [noteId]) // eslint-disable-line react-hooks/exhaustive-deps

  // Don't render if no connections or still loading
  if (connectionCount === 0 || isLoading) {
    return null
  }

  const plural = connectionCount > 1 ? 's' : ''
  const badgeText = t('memoryEcho.connectionsBadge', { count: connectionCount, plural })

  return (
    <div className={cn(
      'inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-400 border border-purple-200 dark:border-purple-800 transition-all duration-150 ease-out',
      isHovered && 'scale-105',
      className
    )}
      onClick={onClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      title={badgeText}
    >
      <Sparkles className="h-2.5 w-2.5 inline-block mr-1" />
      {badgeText}
    </div>
  )
})
