import { Component, OnInit, inject } from '@angular/core'
import { CommonModule } from '@angular/common'
import { FormsModule } from '@angular/forms'
import { Router } from '@angular/router'
import { LiveApiService } from './live-api-service'
import { Notifier } from '@app/core'
import { ActionDropdownComponent, DropdownAction } from '../shared/shared-main/buttons/action-dropdown.component'
import { ButtonComponent } from '../shared/shared-main/buttons/button.component'

interface LiveVideoDisplay {
    id: number
    title: string
    thumbnail?: string
    camera: string
    startTime: string
    endTime: string
  }

@Component({
  selector: "app-schedule-live",
  templateUrl: "./schedule-live.component.html",
  styleUrls: ["./schedule-live.component.scss"],
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ActionDropdownComponent,
    ButtonComponent
  ]
})
export class ScheduleLiveComponent implements OnInit {

  private liveApi = inject(LiveApiService)
  private notifier = inject(Notifier)
  private router = inject(Router)

  liveVideos: LiveVideoDisplay[] = []
  loading = false
  searchQuery = ''

  videoActions: DropdownAction<LiveVideoDisplay>[] = [
    {
      label: 'Delete',
      iconName: 'delete',
      handler: video => this.deleteVideo(video)
    }
  ]

  ngOnInit () {
    this.loadVideos()
  }

  loadVideos () {

    this.loading = true

    this.liveApi.listLiveVideos({
        pagination: {
          start: 0,
          count: 10
        }
      })
      .subscribe({
        next: (response: any) => {
          this.liveVideos = (response.data || []).map((video: any) => {
            console.log("video object", video);
            console.log(
              'Thumbnail URL:',
              '/lazy-static/thumbnails/' + video.thumbnailFilename
            )
            return {
              id: video.id,
              title: video.title,
              thumbnail: video.thumbnailFilename
                ? "/lazy-static/thumbnails/" + video.thumbnailFilename
                : "",
              camera: video.targetCamera,
              startTime: video.startTime,
              endTime: video.endTime,
            };
          });
          this.loading = false;
        },
        error: err => {
          console.error('Error loading live videos:', err)
          this.notifier.error('Failed to load live videos')
          this.loading = false
        }
      })
  }

  get filteredVideos () {

    const query = this.searchQuery.trim().toLowerCase()

    if (!query) return this.liveVideos

    return this.liveVideos.filter(video =>
      video.title.toLowerCase().includes(query) ||
      video.camera.toLowerCase().includes(query)
    )
  }
  openVideoForm (video?: LiveVideoDisplay) {

    if (video) {
        // Edit
        this.router.navigate(['/manage-live', video.id])
      } else {
        // Create
        this.router.navigate(['/manage-live'])
      }
  }

  deleteVideo (video: LiveVideoDisplay) {

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

    this.liveApi.deleteLiveVideo(video.id)
      .subscribe({
        next: () => {
          this.notifier.success('Live video deleted successfully')
          this.loadVideos()
        },
        error: err => {
          console.error('Error deleting live video:', err)
          this.notifier.error('Failed to delete live video')
        }
      })
  }
}
