import { Component, OnInit, inject } from '@angular/core'
import { CommonModule } from '@angular/common'
import { FormsModule } from '@angular/forms'
import { ActivatedRoute, Router } from '@angular/router'
import { EventApiService, EventCreate } from '../+event-hub/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 { ImageInputComponent } from '../shared/shared-forms/image-input.component'


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

  eventId: number | null = null
  eventChannelId: number | null = null
  thumbnailFile: File | null = null
  userChannels: VideoChannel[] = []
  selectedChannelId: number | null = null
  isEditMode = true
  pendingDelete = false
  hasPendingAction = false
  
  formEvent: EventCreate = {
    title: '',
    description: '',
    liveUrl: '',
    startTime: '',
    endTime: '',
    state: 'active'
  }

  ngOnInit() {
    this.loadUserChannels()
    
    // Check if we're editing an existing event
    this.route.params.subscribe(params => {
      if (params['id']) {
        this.eventId = parseInt(params['id'])
        this.isEditMode = false
        this.loadEvent(this.eventId)
      } else {
        this.isEditMode = true
      }
    })
  }

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

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

  loadEvent(eventId: number) {
    this.eventApi.getPublicEvent(eventId).subscribe({
      next: (event: any) => {
        this.eventChannelId = event.channelId
        this.selectedChannelId = event.channelId
        this.formEvent = {
          title: event.title,
          description: event.description || '',
          liveUrl: event.liveUrl || '',
          startTime: this.toDateTimeLocalValue(event.startTime),
          endTime: this.toDateTimeLocalValue(event.endTime),
          state: this.normalizeActionState(event.state)
        }
        this.pendingDelete = false
        this.hasPendingAction = false
      },
      error: (err) => {
        console.error('Error loading event:', err)
        this.notifier.error(this.extractErrorMessage(err))
      }
    })
  }

  normalizeActionState (state: string): 'active' | 'disabled' {
    if (!state) return 'active'

    return state.toLowerCase() === 'disabled' ? 'disabled' : 'active'
  }

  onFileSelected(event: any) {
    if (!this.isEditMode) return
  
    const file = event?.file || event?.target?.files?.[0]
    if (file) {
      this.thumbnailFile = file
    }
  }
  
  saveEvent() {
    if (this.eventId && !this.isEditMode && !this.hasPendingAction) {
      this.notifier.error('Click Edit to enable the form before updating')
      return
    }

    const channelId = this.eventId ? this.eventChannelId : this.selectedChannelId
    if (!this.formEvent.title || !this.formEvent.startTime || !this.formEvent.endTime || !channelId) {
      this.notifier.error('Please fill in required fields')
      return
    }

    const payload: EventCreate = {
      title: this.formEvent.title,
      description: this.formEvent.description || '',
      liveUrl: this.formEvent.liveUrl || '',
      startTime: new Date(this.formEvent.startTime).toISOString(),
      endTime: new Date(this.formEvent.endTime).toISOString(),
      state: this.formEvent.state
    }

    if (this.eventId && this.pendingDelete) {
      this.eventApi.deleteEvent(channelId, this.eventId)
        .subscribe({
          next: () => {
            this.notifier.success('Event deleted successfully')
            this.router.navigate(['/admin-controller/event-hub'])
          },
          error: (err) => {
            console.error('Error deleting event:', err)
            this.notifier.error(this.extractErrorMessage(err))
          }
        })
      return
    }

    if (this.eventId) {
      // Update existing event
      this.eventApi.updateEvent(
        channelId,
        this.eventId,
        this.thumbnailFile ? this.buildMultipartPayload(payload, this.thumbnailFile) : payload
      )
        .subscribe({
          next: () => {
            this.notifier.success('Event updated successfully')
            this.isEditMode = false
            this.pendingDelete = false
            this.hasPendingAction = false
            this.router.navigate(['/admin-controller/event-hub'])
          },
          error: (err) => {
            console.error('Error updating event:', err)
            this.notifier.error(this.extractErrorMessage(err))
          }
        })
    } else {
      // Create new event
      this.eventApi.createEvent(
        channelId,
        this.thumbnailFile ? this.buildMultipartPayload(payload, this.thumbnailFile) : payload
      )
        .subscribe({
          next: () => {
            this.notifier.success('Event created successfully')
            this.router.navigate(['/admin-controller/event-hub'])
          },
          error: (err) => {
            console.error('Error creating event:', err)
            this.notifier.error(this.extractErrorMessage(err))
          }
        })
    }
  }

  cancel() {
    this.router.navigate(['/admin-controller/event-hub'])
  }

  enableEditMode () {
    this.isEditMode = true
  }

  setEventState (state: 'active' | 'disabled') {
    if (!this.eventId || !this.eventChannelId) return

    this.formEvent.state = state
    this.pendingDelete = false
    this.hasPendingAction = true
  }

  deleteCurrentEvent () {
    if (!this.eventId || !this.eventChannelId) return
    if (!confirm(`Mark "${this.formEvent.title}" for deletion? It will be deleted after clicking Update Event.`)) return

    this.pendingDelete = true
    this.hasPendingAction = true
    this.notifier.success('Event marked for deletion. Click Update Event to apply.')
  }

  private extractErrorMessage (err: any): string {
    // Check for single error message in response
    if (err?.body?.detail) {
      return err.body.detail
    }

    // Fallback to generic message
    return 'Failed to save event'
  }

  private toDateTimeLocalValue (dateValue: string): string {
    if (!dateValue) return ''

    const date = new Date(dateValue)
    if (Number.isNaN(date.getTime())) return ''

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return `${year}-${month}-${day}T${hours}:${minutes}`
  }

  private buildMultipartPayload (payload: EventCreate, thumbnailFile: File): FormData {
    const formData = new FormData()
    formData.append('title', payload.title || '')
    formData.append('description', payload.description || '')
    if (payload.liveUrl) formData.append('liveUrl', payload.liveUrl)
    if (payload.startTime) formData.append('startTime', payload.startTime)
    if (payload.endTime) formData.append('endTime', payload.endTime)
    if (payload.state) formData.append('state', payload.state)
    formData.append('thumbnailfile', thumbnailFile)

    return formData
  }
}
