import { NgStyle } from '@angular/common'
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, inject, input, output } from '@angular/core'
import { AuthService, Notifier, User, UserService } from '@app/core'
import { Video } from '@app/shared/shared-main/video/video.model'
import { VideoListParams, VideoService } from '@app/shared/shared-main/video/video.service'
import { objectKeysTyped } from '@peertube/peertube-core-utils'
import { ResultList, VideoSortField } from '@peertube/peertube-models'
import { Observable } from 'rxjs'
import { finalize, map } from 'rxjs/operators'
import { MiniatureDisplayOptions, VideoMiniatureComponent } from '../../shared-video-miniature/video-miniature.component'
import { CustomMarkupComponent } from './shared'

/*
 * Markup component list videos depending on criteria
 */

@Component({
  selector: 'my-videos-list-markup',
  templateUrl: 'videos-list-markup.component.html',
  styleUrls: [ 'videos-list-markup.component.scss' ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ NgStyle, VideoMiniatureComponent ]
})
export class VideosListMarkupComponent implements CustomMarkupComponent, OnInit {
  private auth = inject(AuthService)
  private videoService = inject(VideoService)
  private notifier = inject(Notifier)
  private userService = inject(UserService)
  private cd = inject(ChangeDetectorRef)

  readonly sort = input<string>(undefined)
  readonly categoryOneOf = input<number[]>(undefined)
  readonly languageOneOf = input<string[]>(undefined)
  readonly count = input<number>(undefined)
  readonly onlyDisplayTitle = input<boolean>(undefined)
  readonly isLocal = input<boolean>(undefined)
  readonly isLive = input<boolean>(undefined)
  readonly maxRows = input<number>(undefined)
  readonly channelHandle = input<string>(undefined)
  readonly accountHandle = input<string>(undefined)
  readonly host = input<string>(undefined)

  readonly loaded = output<boolean>()

  videos: Video[]
  user: User

  displayOptions: MiniatureDisplayOptions = {
    date: false,
    views: true,
    by: true,
    avatar: true,
    privacyLabel: false
  }

  limitRowsStyle () {
    if (this.maxRows() <= 0) return {}

    return {
      'grid-template-rows': `repeat(${this.maxRows()}, 1fr)`,
      'grid-auto-rows': '0', // Set height to 0 for autogenerated grid rows
      'overflow-y': 'hidden' // Hide grid items that overflow
    }
  }

  ngOnInit () {
    if (this.onlyDisplayTitle()) {
      for (const key of objectKeysTyped(this.displayOptions)) {
        this.displayOptions[key] = false
      }
    }

    this.userService.getAnonymousOrLoggedUser()
      .subscribe(user => this.user = user)

    this.getVideosObservable()
      .pipe(finalize(() => this.loaded.emit(true)))
      .subscribe({
        next: data => {
          this.videos = data
          this.cd.markForCheck()
        },

        error: err => this.notifier.error($localize`Error in videos list component: ${err.message}`)
      })
  }

  getVideosObservable () {
    const options: VideoListParams = {
      videoPagination: {
        currentPage: 1,
        itemsPerPage: this.count()
      },
      categoryOneOf: this.categoryOneOf(),
      languageOneOf: this.languageOneOf(),
      host: this.host(),
      isLocal: this.isLocal(),
      isLive: this.isLive(),
      sort: this.sort() as VideoSortField,
      skipCount: true
    }

    let obs: Observable<ResultList<Video>>

    const channelHandle = this.channelHandle()
    const accountHandle = this.accountHandle()
    if (channelHandle) {
      obs = this.videoService.listChannelVideos({
        ...options,

        videoChannel: { nameWithHost: channelHandle }
      })
    } else if (accountHandle) {
      obs = this.videoService.listAccountVideos({
        ...options,

        account: { nameWithHost: accountHandle }
      })
    } else {
      obs = this.videoService.listVideos(options)
    }

    return obs.pipe(map(({ data }) => data))
  }
}
