import { CommonModule } from '@angular/common'
import { Component, inject, OnInit, OnDestroy } from '@angular/core'
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router'
import { AuthService, Notifier } from '@app/core'
import { Event } from '@peertube/peertube-models'
import { Subject } from 'rxjs'
import { filter, takeUntil } from 'rxjs/operators'
import { EventApiService } from '../../+event-hub/event-api.service'
import { ButtonComponent } from '../../shared/shared-main/buttons/button.component'

@Component({
  selector: 'app-event-details',
  templateUrl: './event-details.component.html',
  styleUrls: [ './event-details.component.scss' ],
  standalone: true,
  imports: [
    CommonModule,
    RouterLink,
    ButtonComponent,
    RouterOutlet
  ]
})
export class EventDetailsComponent implements OnInit, OnDestroy {
  private route = inject(ActivatedRoute)
  private router = inject(Router)
  private eventApi = inject(EventApiService)
  private notifier = inject(Notifier)
  private auth = inject(AuthService)

  private destroy$ = new Subject<void>()
  hasChildRoute = false

  event: Event | null = null
  loading = true
  notFound = false

  ngOnInit () {
    this.route.params
      .pipe(takeUntil(this.destroy$))
      .subscribe(params => {
        const eventId = params['eventId']
        if (eventId) {
          this.loadEvent(eventId)
        }
      })
      this.hasChildRoute = !!this.route.snapshot.firstChild
  this.router.events
    .pipe(
      filter(event => event instanceof NavigationEnd),
      takeUntil(this.destroy$)
    )
    .subscribe(() => {
      this.hasChildRoute = !!this.route.firstChild
    })
  }

  ngOnDestroy () {
    this.destroy$.next()
    this.destroy$.complete()
  }

  goBack () {
    this.router.navigate([ '/events-hub' ])
  }

  editEvent () {
    if (this.event) {
      this.router.navigate([ '/event-hub-controller/events', this.event.id, 'edit' ])
    }
  }

  private loadEvent (eventId: number) {
    this.loading = true
    this.notFound = false

    this.eventApi.getPublicEvent(eventId).subscribe({
      next: (event) => {
        this.event = event
        this.loading = false
      },
      error: (err) => {
        console.error('Error loading event:', err)
        this.notFound = true
        this.loading = false
        this.notifier.error('Event not found or could not be loaded')
      }
    })
  }

  getThumbnailUrl (): string {
    if (!this.event?.thumbnailFilename) {
      return 'assets/images/favicon.png'
    }
    return '/lazy-static/event-thumbnails/' + this.event.thumbnailFilename
  }

  formatDate (date: Date | string): string {
    return new Date(date).toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  goToRegisterPage () {
    this.router.navigate(['register-eventuser'], {
      relativeTo: this.route
    })
  }
  getEventDuration (): string {
    if (!this.event?.startTime || !this.event?.endTime) {
      return 'Duration not available'
    }

    const start = new Date(this.event.startTime).getTime()
    const end = new Date(this.event.endTime).getTime()
    const durationMs = end - start

    const hours = Math.floor(durationMs / (1000 * 60 * 60))
    const minutes = Math.floor((durationMs % (1000 * 60 * 60)) / (1000 * 60))

    if (hours > 0) {
      return `${hours}h ${minutes}m`
    }
    return `${minutes}m`
  }
}
