import { computed } from 'vue'
import { injectService, SERVICE_TOKENS } from '@/core/di-container'
import type { ReactionService, EventReactions } from '../services/ReactionService'
import { useToast } from '@/core/composables/useToast'

/**
 * Composable for managing reactions in the feed
 */
export function useReactions() {
  const reactionService = injectService<ReactionService>(SERVICE_TOKENS.REACTION_SERVICE)
  const toast = useToast()

  /**
   * Get reactions for a specific event
   */
  const getEventReactions = (eventId: string): EventReactions => {
    if (!reactionService) {
      return {
        eventId,
        likes: 0,
        dislikes: 0,
        totalReactions: 0,
        userHasLiked: false,
        userHasDisliked: false,
        reactions: []
      }
    }
    return reactionService.getEventReactions(eventId)
  }

  /**
   * Subscribe to reactions for a list of event IDs
   */
  const subscribeToReactions = async (eventIds: string[]): Promise<void> => {
    if (!reactionService || eventIds.length === 0) return

    try {
      await reactionService.subscribeToReactions(eventIds)
    } catch (error) {
      console.error('Failed to subscribe to reactions:', error)
    }
  }

  /**
   * Toggle like on an event - like if not liked, unlike if already liked
   */
  const toggleLike = async (eventId: string, eventPubkey: string, eventKind: number): Promise<void> => {
    if (!reactionService) {
      toast.error('Reaction service not available')
      return
    }

    try {
      await reactionService.toggleLikeEvent(eventId, eventPubkey, eventKind)

      // Check if we liked or unliked
      const eventReactions = reactionService.getEventReactions(eventId)
      if (eventReactions.userHasLiked) {
        toast.success('Post liked!')
      } else {
        toast.success('Like removed')
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Failed to toggle reaction'

      if (message.includes('authenticated')) {
        toast.error('Please sign in to react to posts')
      } else if (message.includes('Not connected')) {
        toast.error('Not connected to relays')
      } else {
        toast.error(message)
      }

      console.error('Failed to toggle like:', error)
    }
  }

  /**
   * Get loading state
   */
  const isLoading = computed(() => {
    return reactionService?.isLoading ?? false
  })

  /**
   * Get all event reactions (for debugging)
   */
  const allEventReactions = computed(() => {
    return reactionService?.eventReactions ?? new Map()
  })

  return {
    // Methods
    getEventReactions,
    subscribeToReactions,
    toggleLike,

    // State
    isLoading,
    allEventReactions
  }
}