import { CommonModule } from '@angular/common'
import { Component, OnInit, inject } from '@angular/core'
import { RouterLink } from '@angular/router'
import { AuthService, Notifier } from '@app/core'
import { UserRole, Event } from '@peertube/peertube-models'
import { EventApiService } from '../+event-hub/event-api.service'

@Component({
  selector: 'solt-events',
  templateUrl: './events.component.html',
  styleUrls: [ './events.component.scss' ],
  standalone: true,
  imports: [
    CommonModule,
    RouterLink,
  ]
})
export class EventsComponent implements OnInit {
  private eventApi = inject(EventApiService)
  private notifier = inject(Notifier)

  events: Event[] = []
  loading = false

  ngOnInit () {
    this.loadActiveEvents()
  }

  /**
   * Load active events from the API.
   * Attempts to use backend filtering by state first (if supported),
   * falls back to client-side filtering if needed.
   */
  private loadActiveEvents () {
    this.loading = true

    // Attempt to fetch with server-side filtering for 'active' state
    this.eventApi.listPublicEvents({ state: 'active' }).subscribe({
      next: (response: any) => {
        this.handleEventsResponse(response)
      },
      error: (err) => {
        // If backend doesn't support state filtering, fall back to client-side
        console.warn('Backend may not support state filtering, falling back to client-side filtering:', err)
        this.loadActiveEventsWithClientFilter()
      }
    })
  }

  /**
   * Fallback: Load all events and filter client-side for 'active' state.
   * This ensures compatibility if the backend doesn't support query parameters.
   */
  private loadActiveEventsWithClientFilter () {
    this.eventApi.listPublicEvents().subscribe({
      next: (response: any) => {
        const rawEvents = response.data || response || []

        // Client-side filtering: only keep active events
        this.events = rawEvents.filter((event: any) => {
          const eventState = (event.state || '').toLowerCase()
          return eventState === 'active'
        })

        this.loading = false
      },
      error: (err) => {
        console.error('Error loading events:', err)
        this.notifier.error('Failed to load events')
        this.loading = false
      }
    })
  }

  /**
   * Process the events response from the API.
   * Handles both paginated and non-paginated responses.
   */
  private handleEventsResponse (response: any) {
    try {
      // Handle both paginated { data: [], total: N } and direct array responses
      const rawEvents = response.data || (Array.isArray(response) ? response : [])

      // Map to Event type with proper formatting
      this.events = rawEvents.map((event: any) => ({
        ...event,
        // Ensure thumbnailFilename is available for template
        thumbnailFilename: event.thumbnailFilename || null
      }))

      this.loading = false
    } catch (error) {
      console.error('Error processing events response:', error)
      this.notifier.error('Failed to process events')
      this.loading = false
    }
  }
}
