import { Component, OnInit, inject } from '@angular/core'
import { CommonModule } from '@angular/common'
import { FormsModule } from '@angular/forms'
import { Router } from '@angular/router'
import { EventApiService } from './event-api.service'
import { Notifier } from '@app/core'
import { VideoChannelService } from '../shared/shared-main/channel/video-channel.service'
import { UserService } from '../core/users/user.service'
import { VideoChannel } from '@peertube/peertube-models'
import { ActionDropdownComponent, DropdownAction } from '../shared/shared-main/buttons/action-dropdown.component'
import { ButtonComponent } from '../shared/shared-main/buttons/button.component'

interface EventDisplay {
  id: number
  title: string
  description?: string
  thumbnail?: string
  privacy: string
  state: string
  startTime: string
  endTime: string
  channelId: number
}

@Component({
  selector: 'solt-event-hub',
  templateUrl: './event-hub.component.html',
  styleUrls: ['./event-hub.component.scss'],
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ActionDropdownComponent,
    ButtonComponent
  ]
})
export class EventHubComponent implements OnInit {
  private eventApi = inject(EventApiService)
  private notifier = inject(Notifier)
  private videoChannelService = inject(VideoChannelService)
  private userService = inject(UserService)
  private router = inject(Router)

  events: EventDisplay[] = []
  loading = false
  searchQuery = ''
  filterState: 'ALL' | 'UPCOMING' | 'PAST' = 'ALL'

  // User Channels
  userChannels: VideoChannel[] = []
  selectedChannelId: number | null = null
  eventActions: DropdownAction<EventDisplay>[] = [
    {
      label: 'Delete',
      iconName: 'delete',
      handler: event => this.deleteEvent(event)
    }
  ]

  ngOnInit () {
    this.loadUserChannels()
  }

  loadUserChannels() {
    this.userService.getAnonymousOrLoggedUser().subscribe(user => {
      if (!user || !user.account) {
        this.loadEvents()
        return
      }

      this.videoChannelService.listAccountChannels({ account: user.account })
        .subscribe(res => {
          this.userChannels = res.data
          if (this.userChannels.length > 0) {
            this.selectedChannelId = this.userChannels[0].id
          }

          this.loadEvents()
        })
    })
  }

  loadEvents () {
    this.loading = true
    // const isAdminRoute = this.router.url?.includes('/admin-controller')

    // // For admin pages, load site-wide events (all channels, all states).
    // // Otherwise, load channel-specific events when a channel is selected,
    // // or the public listing when no channel is selected.
    // const eventsLoader = isAdminRoute
    //   ? this.eventApi.listPublicEvents()
    //   : (this.selectedChannelId
    //     ? this.eventApi.listChannelEvents(this.selectedChannelId)
    //     : this.eventApi.listPublicEvents())

    const eventsLoader = this.eventApi.listPublicEvents()

    eventsLoader
      .subscribe({
        next: (response: any) => {
          this.events = (response.data || response || []).map((event: any) => ({
            id: event.id,
            title: event.title,
            description: event.description,
            thumbnail: event.thumbnailFilename ? '/lazy-static/event-thumbnails/' + event.thumbnailFilename : 'assets/images/favicon.png',
            privacy: 'Public',
            state: this.mapEventState(event.state),
            startTime: event.startTime,
            endTime: event.endTime,
            channelId: event.channelId
          }))
          this.loading = false
        },
        error: (err) => {
          console.error('Error loading events:', err)
          this.notifier.error('Failed to load events')
          this.loading = false
        }
      })
  }

  mapEventState (state: string): string {
    const stateMap: { [key: string]: string } = {
      'active': 'ACTIVE',
      'scheduled': 'UPCOMING',
      'completed': 'PAST',
      'draft': 'DRAFT',
      'disabled': 'DISABLED'
    }
    return stateMap[state.toLowerCase()] || state.toUpperCase()
  }

  get filteredEvents () {
    const query = this.searchQuery.trim().toLowerCase()
    const now = Date.now()

    return this.events.filter(event => {
      const eventStart = new Date(event.startTime).getTime()
      const stateMatch =
        this.filterState === 'ALL' ||
        (this.filterState === 'UPCOMING' && eventStart > now) ||
        (this.filterState === 'PAST' && eventStart <= now)

      if (!stateMatch) return false

      if (!query) return true

      return event.title.toLowerCase().includes(query) ||
        (event.description || '').toLowerCase().includes(query)
    })
  }

  openEventForm (event?: EventDisplay) {
    if (event) {
      // Navigate to edit screen
      this.router.navigate(['/manage-event', event.id])
    } else {
      // Navigate to create screen
      this.router.navigate(['/manage-event'])
    }
  }

  deleteEvent (event: EventDisplay) {
    if (!confirm(`Are you sure you want to delete "${event.title}"?`)) {
      return
    }

    const channelId = event.channelId
    this.eventApi.deleteEvent(channelId, event.id)
      .subscribe({
        next: () => {
          this.notifier.success('Event deleted successfully')
          this.loadEvents()
        },
        error: (err) => {
          console.error('Error deleting event:', err)
          this.notifier.error('Failed to delete event')
        }
      })
  }

  updateEventState (event: EventDisplay, newState: string) {
    const channelId = event.channelId
    const stateMap: { [key: string]: string } = {
      'LIVE': 'active',
      'UPCOMING': 'scheduled',
      'PAST': 'completed',
      'DRAFT': 'draft',
      'DISABLED': 'disabled'
    }

    this.eventApi.updateEventState(channelId, event.id, { state: stateMap[newState] as any })
      .subscribe({
        next: () => {
          this.notifier.success('Event state updated')
          this.loadEvents()
        },
        error: (err) => {
          console.error('Error updating event state:', err)
          this.notifier.error('Failed to update event state')
        }
      })
  }
}
