import { useEffect } from 'react'
import type { BaseItemDto } from '../api/types'
import { useEpisodes, useNextUpForSeries } from './use-jellyfin'
import { useQueueStore } from '../stores/queue-store'

type EpisodeItem = BaseItemDto & {
  SeriesId?: string | null
  SeasonId?: string | null
}

export function usePlayerNavigation(item: BaseItemDto | null | undefined, itemId: string | undefined) {
  const episode = item?.Type === 'Episode' ? (item as EpisodeItem) : null
  const seriesId = episode?.SeriesId || undefined
  const seasonId = episode?.SeasonId || undefined

  const { data: nextUpItem } = useNextUpForSeries(seriesId)
  const { data: seasonEpisodes = [] } = useEpisodes(seriesId, seasonId)
  const currentEpisodeIndex = seasonEpisodes.findIndex(e => e.Id === itemId)
  const previousEpisode = currentEpisodeIndex > 0 ? seasonEpisodes[currentEpisodeIndex - 1] : null
  const siblingNextEpisode =
    currentEpisodeIndex >= 0 && currentEpisodeIndex < seasonEpisodes.length - 1
      ? seasonEpisodes[currentEpisodeIndex + 1]
      : null
  const nextEpisode = siblingNextEpisode || nextUpItem || null

  const queueItems = useQueueStore(s => s.items)
  const queueIndex = useQueueStore(s => s.index)
  const setQueueIndex = useQueueStore(s => s.setIndex)
  const queuePosition = queueItems.findIndex(it => it.Id === itemId)
  const queueActive = queuePosition >= 0
  const queuePrev = queueActive && queuePosition > 0 ? queueItems[queuePosition - 1] : null
  const queueNext = queueActive && queuePosition < queueItems.length - 1 ? queueItems[queuePosition + 1] : null

  useEffect(() => {
    if (queueActive && queuePosition !== queueIndex) setQueueIndex(queuePosition)
  }, [queueActive, queuePosition, queueIndex, setQueueIndex])

  return {
    seriesId,
    seasonId,
    seasonEpisodes,
    previousEpisode,
    nextEpisode,
    nextUpItem,
    queueActive,
    queueNext,
    previousItem: queuePrev || previousEpisode || null,
    nextItem: queueNext || nextEpisode || null,
  }
}
