<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { formatDistanceToNow } from 'date-fns'
import { Megaphone, RefreshCw, AlertCircle } from 'lucide-vue-next'
import { config, configUtils } from '@/lib/config'
import { injectService, SERVICE_TOKENS } from '@/core/di-container'

const props = defineProps<{
  relays?: string[]
  feedType?: 'all' | 'announcements' | 'events' | 'general'
}>()

const relayHub = injectService(SERVICE_TOKENS.RELAY_HUB) as any

// Reactive state
const notes = ref<any[]>([])
const isLoading = ref(false)
const error = ref<Error | null>(null)
const isConnected = ref(false)

// Get admin/moderator pubkeys from centralized config
const adminPubkeys = config.nostr.adminPubkeys

// Check if we have admin pubkeys configured
const hasAdminPubkeys = computed(() => adminPubkeys.length > 0)

// Get feed title and description based on type
const feedTitle = computed(() => {
  switch (props.feedType) {
    case 'announcements':
      return 'Community Announcements'
    case 'events':
      return 'Events & Calendar'
    case 'general':
      return 'General Discussion'
    default:
      return 'Community Feed'
  }
})

const feedDescription = computed(() => {
  switch (props.feedType) {
    case 'announcements':
      return 'Important announcements from community administrators'
    case 'events':
      return 'Upcoming events and calendar updates'
    case 'general':
      return 'Community discussions and general posts'
    default:
      return 'Latest posts from the community'
  }
})

// Check if a post is from an admin
function isAdminPost(pubkey: string): boolean {
  return configUtils.isAdminPubkey(pubkey)
}

// Load notes from relays
async function loadNotes() {
  if (!hasAdminPubkeys.value && props.feedType === 'announcements') {
    notes.value = []
    return
  }

  try {
    isLoading.value = true
    error.value = null

    // Connect to relay hub if not already connected
    if (!relayHub.isConnected) {
      await relayHub.connect()
    }

    isConnected.value = relayHub.isConnected

    if (!isConnected.value) {
      throw new Error('Failed to connect to Nostr relays')
    }

    // Configure filters based on feed type
    const filters: any[] = [{
      kinds: [1], // TEXT_NOTE
      limit: 50
    }]

    // Filter by authors for announcements
    if (props.feedType === 'announcements' && hasAdminPubkeys.value) {
      filters[0].authors = adminPubkeys
    }

    // Query events from relays
    const events = await relayHub.queryEvents(filters)
    
    // Process and filter events
    let processedNotes = events.map((event: any) => ({
      id: event.id,
      pubkey: event.pubkey,
      content: event.content,
      created_at: event.created_at,
      tags: event.tags || [],
      // Extract mentions from tags
      mentions: event.tags?.filter((tag: any[]) => tag[0] === 'p').map((tag: any[]) => tag[1]) || [],
      // Check if it's a reply
      isReply: event.tags?.some((tag: any[]) => tag[0] === 'e' && tag[3] === 'reply'),
      replyTo: event.tags?.find((tag: any[]) => tag[0] === 'e' && tag[3] === 'reply')?.[1]
    }))

    // Sort by creation time (newest first)
    processedNotes.sort((a: any, b: any) => b.created_at - a.created_at)

    // For general feed, exclude admin posts
    if (props.feedType === 'general' && hasAdminPubkeys.value) {
      processedNotes = processedNotes.filter((note: any) => !isAdminPost(note.pubkey))
    }

    notes.value = processedNotes

  } catch (err) {
    const errorObj = err instanceof Error ? err : new Error('Failed to load notes')
    error.value = errorObj
    console.error('Failed to load notes:', errorObj)
  } finally {
    isLoading.value = false
  }
}

// Refresh the feed
async function refreshFeed() {
  await loadNotes()
}

// Subscribe to real-time updates
let unsubscribe: (() => void) | null = null

async function startRealtimeSubscription() {
  if (!relayHub.isConnected) return

  try {
    const filters: any[] = [{
      kinds: [1], // TEXT_NOTE
      limit: 10
    }]

    if (props.feedType === 'announcements' && hasAdminPubkeys.value) {
      filters[0].authors = adminPubkeys
    }

    unsubscribe = relayHub.subscribe({
      id: `feed-${props.feedType || 'all'}`,
      filters,
      onEvent: (event: any) => {
        // Add new note to the beginning of the list
        const newNote = {
          id: event.id,
          pubkey: event.pubkey,
          content: event.content,
          created_at: event.created_at,
          tags: event.tags || [],
          mentions: event.tags?.filter((tag: any[]) => tag[0] === 'p').map((tag: any[]) => tag[1]) || [],
          isReply: event.tags?.some((tag: any[]) => tag[0] === 'e' && tag[3] === 'reply'),
          replyTo: event.tags?.find((tag: any[]) => tag[0] === 'e' && tag[3] === 'reply')?.[1]
        }

        // Check if note should be included
        let shouldInclude = true
        if (props.feedType === 'announcements' && !isAdminPost(event.pubkey)) {
          shouldInclude = false
        }
        if (props.feedType === 'general' && isAdminPost(event.pubkey)) {
          shouldInclude = false
        }

        if (shouldInclude) {
          notes.value.unshift(newNote)
          // Limit array size
          if (notes.value.length > 100) {
            notes.value = notes.value.slice(0, 100)
          }
        }
      }
    })
  } catch (error) {
    console.error('Failed to start real-time subscription:', error)
  }
}

// Cleanup subscription
function cleanup() {
  if (unsubscribe) {
    unsubscribe()
    unsubscribe = null
  }
}

onMounted(async () => {
  await loadNotes()
  await startRealtimeSubscription()
})

onUnmounted(() => {
  cleanup()
})
</script>

<template>
  <Card class="w-full">
    <CardHeader>
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-2">
          <Megaphone class="h-5 w-5 text-primary" />
          <div>
            <CardTitle>{{ feedTitle }}</CardTitle>
            <CardDescription>{{ feedDescription }}</CardDescription>
          </div>
        </div>
        <Button 
          variant="outline" 
          size="sm" 
          @click="refreshFeed"
          :disabled="isLoading"
          class="gap-2"
        >
          <RefreshCw :class="{ 'animate-spin': isLoading }" class="h-4 w-4" />
          Refresh
        </Button>
      </div>
    </CardHeader>

    <CardContent>
      <!-- Connection Status -->
      <div v-if="!isConnected && !isLoading" class="mb-4 p-3 bg-yellow-50 dark:bg-yellow-950 border border-yellow-200 dark:border-yellow-800 rounded-lg">
        <div class="flex items-center gap-2 text-yellow-800 dark:text-yellow-200">
          <AlertCircle class="h-4 w-4" />
          <span class="text-sm">Not connected to relays</span>
        </div>
      </div>

      <!-- Loading State -->
      <div v-if="isLoading" class="flex items-center justify-center py-8">
        <div class="flex items-center gap-2">
          <RefreshCw class="h-4 w-4 animate-spin" />
          <span class="text-muted-foreground">Loading announcements...</span>
        </div>
      </div>

      <!-- Error State -->
      <div v-else-if="error" class="text-center py-8">
        <div class="flex items-center justify-center gap-2 text-destructive mb-4">
          <AlertCircle class="h-5 w-5" />
          <span>Failed to load announcements</span>
        </div>
        <p class="text-sm text-muted-foreground mb-4">{{ error.message }}</p>
        <Button @click="refreshFeed" variant="outline">Try Again</Button>
      </div>

      <!-- No Admin Pubkeys Warning -->
      <div v-else-if="!hasAdminPubkeys && props.feedType === 'announcements'" class="text-center py-8">
        <div class="flex items-center justify-center gap-2 text-muted-foreground mb-4">
          <Megaphone class="h-5 w-5" />
          <span>No admin pubkeys configured</span>
        </div>
        <p class="text-sm text-muted-foreground">
          Community announcements will appear here once admin pubkeys are configured.
        </p>
      </div>

      <!-- No Notes -->
      <div v-else-if="notes.length === 0" class="text-center py-8">
        <div class="flex items-center justify-center gap-2 text-muted-foreground mb-4">
          <Megaphone class="h-5 w-5" />
          <span>No announcements yet</span>
        </div>
        <p class="text-sm text-muted-foreground">
          Check back later for community updates and announcements.
        </p>
      </div>

      <!-- Notes List -->
      <ScrollArea v-else class="h-[400px] pr-4">
        <div class="space-y-4">
          <div 
            v-for="note in notes" 
            :key="note.id"
            class="p-4 border rounded-lg hover:bg-accent/50 transition-colors"
          >
            <!-- Note Header -->
            <div class="flex items-start justify-between mb-2">
              <div class="flex items-center gap-2">
                <Badge 
                  v-if="isAdminPost(note.pubkey)" 
                  variant="default" 
                  class="text-xs"
                >
                  Admin
                </Badge>
                <Badge 
                  v-if="note.isReply" 
                  variant="secondary" 
                  class="text-xs"
                >
                  Reply
                </Badge>
                <span class="text-xs text-muted-foreground">
                  {{ formatDistanceToNow(note.created_at * 1000, { addSuffix: true }) }}
                </span>
              </div>
            </div>

            <!-- Note Content -->
            <div class="text-sm leading-relaxed whitespace-pre-wrap">
              {{ note.content }}
            </div>

            <!-- Note Footer -->
            <div v-if="note.mentions.length > 0" class="mt-2 pt-2 border-t">
              <div class="flex items-center gap-1 text-xs text-muted-foreground">
                <span>Mentions:</span>
                <span v-for="mention in note.mentions.slice(0, 3)" :key="mention" class="font-mono">
                  {{ mention.slice(0, 8) }}...
                </span>
                <span v-if="note.mentions.length > 3" class="text-muted-foreground">
                  +{{ note.mentions.length - 3 }} more
                </span>
              </div>
            </div>
          </div>
        </div>
      </ScrollArea>
    </CardContent>
  </Card>
</template>
