import { useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTmdbDiscoverMovies, useTmdbDiscoverTv } from '../../hooks/use-tmdb'
import { useLibraryByTmdbId } from '../../hooks/use-jellyfin'
import { mapTmdbToJf } from '../../lib/tmdb-mapping'
import PosterCard from '../../components/ui/PosterCard'
import { usePosterGridClasses } from '../../lib/density'
import { filtersToTmdbParams, type DiscoverFilterState } from '../../components/discover/DiscoverFilters'
import type { BaseItemDto } from '../../api/types'

/**
 * Shown when any filter is active or sort has been changed from the default.
 * Renders a single grid of TMDB results constrained by the filter selections,
 * with optional library-hide.
 */
export function FilteredGrid({ filters }: { filters: DiscoverFilterState }) {
  const navigate = useNavigate()
  const lib = useLibraryByTmdbId()
  const grid = usePosterGridClasses()
  const params = useMemo(() => filtersToTmdbParams(filters), [filters])
  const moviesQ = useTmdbDiscoverMovies(filters.kind === 'movie' ? params : ({} as Record<string, string>))
  const tvQ = useTmdbDiscoverTv(filters.kind === 'tv' ? params : ({} as Record<string, string>))
  const data = filters.kind === 'movie' ? moviesQ.data : tvQ.data
  const isLoading = filters.kind === 'movie' ? moviesQ.isLoading : tvQ.isLoading

  const items = useMemo(() => {
    const raw = (data?.results || []).map(m => ({
      ...m,
      media_type: filters.kind === 'movie' ? 'movie' : 'tv',
    }))
    let list = raw
    if (filters.hideOwned && lib.data) {
      list = list.filter(m => !lib.data!.has(String(m.id)))
    }
    return mapTmdbToJf(list, lib.data) as BaseItemDto[]
  }, [data, filters.kind, filters.hideOwned, lib.data])

  return (
    <div className="px-7 pt-6">
      <div className="mb-4 flex items-center justify-between gap-3">
        <p className="text-[12px] text-text-3 tracking-tight">
          {isLoading ? (
            'Searching...'
          ) : (
            <>
              <span className="tabular-nums text-text-1 font-semibold">{items.length}</span>
              <span className="text-text-3"> matching {filters.kind === 'movie' ? 'movies' : 'shows'}</span>
              {filters.hideOwned && (
                <span className="text-text-4"> (excluding your library)</span>
              )}
            </>
          )}
        </p>
      </div>

      {isLoading ? (
        <div className={grid}>
          {Array.from({ length: 12 }).map((_, i) => (
            <div key={i}>
              <div className="skeleton aspect-[2/3] rounded-lg" />
              <div className="mt-2.5 space-y-1.5">
                <div className="skeleton h-3 w-3/4 rounded" />
                <div className="skeleton h-2.5 w-1/2 rounded" />
              </div>
            </div>
          ))}
        </div>
      ) : items.length === 0 ? (
        <div className="py-20 text-center max-w-md mx-auto">
          <p className="font-display text-[18px] text-text-1 font-semibold tracking-tight mb-2">
            No matches
          </p>
          <p className="text-[13px] text-text-3 leading-relaxed">
            Loosen the filters to see more results. Reduce the minimum rating, expand the year range, or clear genre selections.
          </p>
        </div>
      ) : (
        <div className={grid}>
          {items.map((item, i) => (
            <PosterCard
              key={item.Id || i}
              item={item}
              priority={i < 6}
              onClick={() => item.Id && navigate(`/item/${item.Id}`)}
            />
          ))}
        </div>
      )}
    </div>
  )
}
