import { useMemo } from 'react'
import { useTmdbDiscoverMovies, useTmdbDiscoverTv } from '../../hooks/use-tmdb'
import { useLibraryByTmdbId } from '../../hooks/use-jellyfin'
import { mapTmdbToJf } from '../../lib/tmdb-mapping'
import ContentRow from './ContentRow'

interface Props {
  /** TMDB company id (for movie studios) or network id (for TV networks). */
  brandId: number
  label: string
  subtitle?: string
  /** Decides which discover endpoint to hit. */
  kind: 'movie' | 'tv'
}

/**
 * One row sourced from TMDB discover with a single `with_companies` /
 * `with_networks` filter. Sorted by popularity descending so the row
 * leads with the brand's most recognisable titles.
 */
export default function BrandRow({ brandId, label, subtitle, kind }: Props) {
  const movieParams = kind === 'movie' ? { with_companies: String(brandId), sort_by: 'popularity.desc' } : ({} as Record<string, string>)
  const tvParams = kind === 'tv' ? { with_networks: String(brandId), sort_by: 'popularity.desc' } : ({} as Record<string, string>)

  const movieDiscover = useTmdbDiscoverMovies(movieParams)
  const tvDiscover = useTmdbDiscoverTv(tvParams)
  const libraryByTmdbId = useLibraryByTmdbId()

  const items = useMemo(() => {
    const raw = kind === 'movie'
      ? (movieDiscover.data?.results || []).map(m => ({ ...m, media_type: 'movie' }))
      : (tvDiscover.data?.results || []).map(m => ({ ...m, media_type: 'tv' }))
    return mapTmdbToJf(raw.slice(0, 18), libraryByTmdbId.data)
  }, [kind, movieDiscover.data, tvDiscover.data, libraryByTmdbId.data])

  if (items.length === 0) return null
  return (
    <ContentRow
      title={label}
      subtitle={subtitle}
      items={items}
      layoutKey={`brand_${kind}_${brandId}`}
    />
  )
}
