import { useNavigate } from 'react-router-dom'
import { motion } from 'framer-motion'
import { useLibraryItems } from '../../hooks/use-jellyfin'
import { usePosterGridClasses } from '../../lib/density'
import PosterCard from '../ui/PosterCard'

interface Props {
  itemId: string
  title: string
  collectionType?: string
}

export default function FolderView({ itemId, title, collectionType }: Props) {
  const navigate = useNavigate()

  let includeItemTypes: string[] | undefined
  if (collectionType === 'tvshows') includeItemTypes = ['Series']
  else if (collectionType === 'movies') includeItemTypes = ['Movie']
  else if (collectionType === 'music') includeItemTypes = ['MusicAlbum', 'MusicArtist']

  const { data, isLoading } = useLibraryItems(itemId, {
    sortBy: ['SortName'],
    sortOrder: ['Ascending'],
    includeItemTypes,
    limit: 200,
  })

  const items = data?.Items || []
  const gridCls = usePosterGridClasses()

  return (
    <div className="py-8 px-7">
      <h1 className="text-2xl font-semibold text-text-1 mb-6 tracking-tight font-display">{title}</h1>
      {isLoading ? (
        <PosterGridSkeleton />
      ) : items.length === 0 ? (
        <p className="text-[13px] text-text-4">No items found.</p>
      ) : (
        <div className={gridCls}>
          {items.map((item, i) => (
            <motion.div
              key={item.Id}
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3, delay: Math.min(i * 0.015, 0.3) }}
            >
              <PosterCard item={item} priority={i < 12} onClick={() => item.Id && navigate(`/item/${item.Id}`)} />
            </motion.div>
          ))}
        </div>
      )}
    </div>
  )
}

function PosterGridSkeleton() {
  const gridCls = usePosterGridClasses()
  return (
    <div className={gridCls}>
      {Array.from({ length: 18 }).map((_, i) => (
        <div key={i}>
          <div className="skeleton aspect-[2/3] rounded-lg" />
          <div className="mt-2 space-y-1">
            <div className="skeleton h-3 w-3/4 rounded" />
            <div className="skeleton h-2.5 w-1/2 rounded" />
          </div>
        </div>
      ))}
    </div>
  )
}
