import { ref, computed } from 'vue'
import { injectService, SERVICE_TOKENS } from '@/core/di-container'
import type { ProfileService } from '../services/ProfileService'

/**
 * Composable for managing user profiles in the feed
 */
export function useProfiles() {
  const profileService = injectService<ProfileService>(SERVICE_TOKENS.PROFILE_SERVICE)

  // Reactive state
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  /**
   * Get display name for a pubkey
   */
  const getDisplayName = (pubkey: string): string => {
    if (!profileService) return formatPubkey(pubkey)
    return profileService.getDisplayName(pubkey)
  }

  /**
   * Fetch profiles for a list of pubkeys
   */
  const fetchProfiles = async (pubkeys: string[]): Promise<void> => {
    if (!profileService || pubkeys.length === 0) return

    try {
      isLoading.value = true
      error.value = null
      await profileService.fetchProfiles(pubkeys)
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to fetch profiles'
      console.error('Failed to fetch profiles:', err)
    } finally {
      isLoading.value = false
    }
  }

  /**
   * Subscribe to profile updates for active users
   */
  const subscribeToProfileUpdates = async (pubkeys: string[]): Promise<void> => {
    if (!profileService) return

    try {
      await profileService.subscribeToProfileUpdates(pubkeys)
    } catch (err) {
      console.error('Failed to subscribe to profile updates:', err)
    }
  }

  /**
   * Get full profile for a pubkey
   */
  const getProfile = async (pubkey: string) => {
    if (!profileService) return null
    return await profileService.getProfile(pubkey)
  }

  /**
   * Format pubkey as fallback display name
   */
  const formatPubkey = (pubkey: string): string => {
    return `${pubkey.slice(0, 8)}...${pubkey.slice(-4)}`
  }

  /**
   * Get all cached profiles
   */
  const profiles = computed(() => {
    if (!profileService) return new Map()
    return profileService.profiles
  })

  return {
    // State
    isLoading,
    error,
    profiles,

    // Methods
    getDisplayName,
    fetchProfiles,
    subscribeToProfileUpdates,
    getProfile,
    formatPubkey
  }
}