import { computed, ref, onMounted, onUnmounted, watch } from 'vue'
import { injectService, SERVICE_TOKENS } from '@/core/di-container'
import type { FeedService, FeedConfig, ContentFilter } from '../services/FeedService'

export interface UseFeedConfig {
  feedType: 'announcements' | 'general' | 'mentions' | 'events' | 'all' | 'custom'
  maxPosts?: number
  refreshInterval?: number
  adminPubkeys?: string[]
  contentFilters?: ContentFilter[]
}

export function useFeed(config: UseFeedConfig) {
  const feedService = injectService<FeedService>(SERVICE_TOKENS.FEED_SERVICE)

  console.log('useFeed: FeedService injected:', !!feedService)
  if (!feedService) {
    console.error('useFeed: FeedService not available from DI container')
  }

  let refreshTimer: number | null = null

  // Convert to FeedService config
  const feedConfig: FeedConfig = {
    feedType: config.feedType,
    maxPosts: config.maxPosts,
    adminPubkeys: config.adminPubkeys,
    contentFilters: config.contentFilters
  }

  const filteredPosts = computed(() => {
    if (!feedService) return []
    return feedService.getFilteredPosts(feedConfig)
  })

  const threadedPosts = computed(() => {
    if (!feedService) return []
    const posts = feedService.getFilteredPosts(feedConfig)
    return feedService.buildThreadedPosts(posts)
  })

  const loadFeed = async () => {
    console.log('useFeed: loadFeed called, feedService available:', !!feedService)
    if (!feedService) {
      console.error('FeedService not available')
      return
    }

    console.log('useFeed: calling feedService.subscribeFeed with config:', feedConfig)
    try {
      await feedService.subscribeFeed(feedConfig)
      console.log('useFeed: subscribeFeed completed')
    } catch (err) {
      console.error('Failed to load feed:', err)
    }
  }

  const refreshFeed = async () => {
    if (!feedService) return
    await feedService.refreshFeed()
  }

  const startAutoRefresh = () => {
    if (config.refreshInterval && config.refreshInterval > 0) {
      refreshTimer = setInterval(refreshFeed, config.refreshInterval) as unknown as number
    }
  }

  const stopAutoRefresh = () => {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
  }

  // Lifecycle
  onMounted(() => {
    console.log('useFeed: onMounted called')
    loadFeed()
    startAutoRefresh()
  })

  onUnmounted(() => {
    stopAutoRefresh()
  })

  // Debug posts reactivity
  watch(filteredPosts, (newPosts) => {
    console.log('useFeed: Posts updated, count:', newPosts.length)
  }, { immediate: true })

  return {
    posts: filteredPosts,
    threadedPosts,
    isLoading: feedService?.isLoading ?? ref(false),
    error: feedService?.error ?? ref(null),
    refreshFeed,
    loadFeed
  }
}