import { useQuery } from '@tanstack/react-query'
import { getCollection, getMovieFull } from '../api/tmdb'
import { useLibraryByTmdbId } from './use-jellyfin'
import type { BaseItemDto } from '../api/types'
import { getTmdbId } from '../lib/item-types'

/**
 * For a movie, lazy-fetch its TMDB collection (if any) and compute the
 * user's progress through it. Returns null when the movie isn't part of
 * a collection or until both fetches resolve.
 *
 * Gated by an `armed` flag (typically the same hover-delay used by the
 * trailer hook) so we don't burn N+1 TMDB requests on first paint of a
 * library grid.
 */
export function useCollectionMeter(
  item: BaseItemDto | null | undefined,
  armed: boolean,
) {
  const tmdbId = getTmdbId(item)
  const numericTmdb = tmdbId ? Number(tmdbId) : null
  const isMovie = item?.Type === 'Movie'

  const movieQ = useQuery({
    queryKey: ['tmdb', 'movie-full', numericTmdb],
    queryFn: () => (numericTmdb ? getMovieFull(numericTmdb) : null),
    enabled: !!numericTmdb && isMovie && armed,
    staleTime: 24 * 60 * 60 * 1000,
  })
  const collectionId = movieQ.data?.belongs_to_collection?.id ?? null

  const colQ = useQuery({
    queryKey: ['tmdb', 'collection', collectionId],
    queryFn: () => (collectionId ? getCollection(collectionId) : null),
    enabled: !!collectionId && armed,
    staleTime: 7 * 24 * 60 * 60 * 1000,
  })

  const libQ = useLibraryByTmdbId()

  if (!collectionId || !colQ.data || !libQ.data) return null
  const parts = colQ.data.parts || []
  if (parts.length < 2) return null
  let inLibrary = 0
  let watched = 0
  for (const p of parts) {
    const local = libQ.data.get(String(p.id))
    if (local) {
      inLibrary++
      if (local.played) watched++
    }
  }
  return {
    collectionName: movieQ.data?.belongs_to_collection?.name || colQ.data.name,
    total: parts.length,
    inLibrary,
    watched,
  }
}
