import { GenreHeader } from '@/components/GenreHeader'
import { SongCard } from '@/components/SongCard'

interface PageProps {
  params: Promise<{ slug: string }>
}

async function getGenreSongs(slug: string) {
  const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/discover/genres/${slug}`, {
    cache: 'no-store',
  })
  if (!res.ok) throw new Error('Genre not found')
  const data = await res.json()
  return data
}

export default async function GenrePage({ params }: PageProps) {
  const { slug } = await params
  const { genre, songs } = await getGenreSongs(slug)

  return (
    <main className="min-h-screen bg-zinc-950">
      <GenreHeader
        name={genre.name}
        description={genre.description}
        songCount={songs?.length || 0}
      />

      <div className="max-w-7xl mx-auto px-4 py-8">
        {songs && songs.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {songs.map((song: any) => (
              <SongCard
                key={song.id}
                id={song.id}
                title={song.title}
                artistName={song.artist?.name || 'Unknown Artist'}
                coverUrl={song.coverUrl || song.album?.coverUrl}
                duration={song.duration || 0}
                plays={song.plays}
              />
            ))}
          </div>
        ) : (
          <div className="text-center py-16">
            <p className="text-xl text-zinc-400 mb-4">No songs found in this genre</p>
            <p className="text-zinc-500">Check back later for new releases</p>
          </div>
        )}
      </div>
    </main>
  )
}
