"use client"

import Image from "next/image"
import Link from "next/link"
import { useParams } from "next/navigation"
import { ChevronLeft, Play, Pause, Loader2 } from "lucide-react"
import { BottomNav } from "@/components/bottom-nav"
import { SectionHeader } from "@/components/section-header"
import { usePlayer } from "@/components/player-provider"
import useSWR from "swr"

const fetcher = (url: string) => fetch(url).then((res) => res.json())

function formatDuration(ms: number) {
  const totalSeconds = Math.floor(ms / 1000)
  const minutes = Math.floor(totalSeconds / 60)
  const seconds = totalSeconds % 60
  return `${minutes}:${seconds.toString().padStart(2, "0")}`
}

const genreColors: Record<string, string> = {
  electronic: "from-violet-600 to-indigo-800",
  pop: "from-pink-500 to-rose-600",
  rock: "from-red-600 to-orange-700",
  hiphop: "from-yellow-600 to-amber-800",
  jazz: "from-blue-600 to-cyan-700",
  classical: "from-purple-600 to-violet-800",
  rnb: "from-fuchsia-600 to-pink-700",
  reggae: "from-green-600 to-emerald-700",
  default: "from-gray-600 to-gray-800",
}

export default function GenrePage() {
  const { id } = useParams<{ id: string }>()

  const { data: genreData, isLoading: genreLoading } = useSWR(`/api/genres/${id}`, fetcher)

  const { data: tracksData, isLoading: tracksLoading } = useSWR(
    `/api/tracks?genre_id=${id}&status=published&limit=20`,
    fetcher,
  )

  const { data: albumsData, isLoading: albumsLoading } = useSWR(
    `/api/albums?genre_id=${id}&status=published&limit=8`,
    fetcher,
  )

  const { data: playlistsData, isLoading: playlistsLoading } = useSWR(`/api/playlists?genre_id=${id}&limit=6`, fetcher)

  const { playTrack, playAlbum, currentTrack, isPlaying, togglePlay } = usePlayer()

  const genre = genreData?.genre || { name: "Genre", id }
  const tracks = tracksData?.data || []
  const albums = albumsData?.albums || []
  const playlists = playlistsData?.playlists || []

  const genreColor = genreColors[genre.slug || id] || genreColors.default

  const playerTracks = tracks.map((t: any) => ({
    id: t.id,
    title: t.title,
    artist: t.artist_name || "Unknown Artist",
    image: t.cover_url || "/abstract-music-album.png",
    duration: Math.floor((t.duration_ms || 0) / 1000),
    audioUrl: t.audio_url,
  }))

  const isGenrePlaying = playerTracks.some((t: any) => t.id === currentTrack?.id) && isPlaying

  const handlePlayGenre = () => {
    if (isGenrePlaying) {
      togglePlay()
    } else if (playerTracks.length > 0) {
      playAlbum(playerTracks, 0)
    }
  }

  const isLoading = genreLoading || tracksLoading

  return (
    <div className="min-h-screen bg-background pb-24">
      {/* Hero */}
      <div className={`relative h-48 bg-gradient-to-br ${genreColor}`}>
        <div className="absolute inset-0 bg-gradient-to-t from-background to-transparent" />

        {/* Header */}
        <div className="absolute left-0 right-0 top-0 z-10 flex items-center justify-between p-4">
          <Link href="/search" className="rounded-full bg-black/30 p-2 text-white hover:bg-black/50">
            <ChevronLeft className="h-5 w-5" />
          </Link>
          <button
            onClick={handlePlayGenre}
            disabled={playerTracks.length === 0}
            className="flex h-12 w-12 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg disabled:opacity-50"
          >
            {isGenrePlaying ? <Pause className="h-5 w-5" /> : <Play className="h-5 w-5 ml-0.5" />}
          </button>
        </div>

        {/* Genre Title */}
        <div className="absolute bottom-4 left-4 right-4 z-10">
          <h1 className="text-3xl font-bold text-white">{genre.name}</h1>
          <p className="text-white/70">Découvrez le meilleur de ce genre</p>
        </div>
      </div>

      <div className="mx-auto max-w-md px-4 py-6">
        {isLoading ? (
          <div className="flex items-center justify-center py-16">
            <Loader2 className="w-8 h-8 animate-spin text-purple-500" />
          </div>
        ) : (
          <>
            {/* Popular Albums */}
            {albums.length > 0 && (
              <section className="mb-8">
                <SectionHeader title="Albums Populaires" />
                <div className="mt-4 grid grid-cols-2 gap-4">
                  {albums.map((album: any) => (
                    <Link key={album.id} href={`/album/${album.id}`} className="group">
                      <div className="relative mb-2 aspect-square overflow-hidden rounded-xl">
                        <Image
                          src={album.cover_url || "/abstract-music-album.png"}
                          alt={album.title}
                          fill
                          className="object-cover transition-transform group-hover:scale-105"
                        />
                        <div className="absolute inset-0 flex items-center justify-center bg-black/0 opacity-0 transition-all group-hover:bg-black/40 group-hover:opacity-100">
                          <div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary text-primary-foreground">
                            <Play className="h-5 w-5 ml-0.5" />
                          </div>
                        </div>
                      </div>
                      <p className="truncate font-medium text-foreground">{album.title}</p>
                      <p className="truncate text-sm text-muted-foreground">{album.artist_name || "Various Artists"}</p>
                    </Link>
                  ))}
                </div>
              </section>
            )}

            {/* Playlists */}
            {playlists.length > 0 && (
              <section className="mb-8">
                <SectionHeader title="Playlists" />
                <div className="mt-4 space-y-2">
                  {playlists.map((playlist: any) => (
                    <Link
                      key={playlist.id}
                      href={`/playlist/${playlist.id}`}
                      className="flex items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary"
                    >
                      <div className="relative h-14 w-14 flex-shrink-0 overflow-hidden rounded-lg">
                        <Image
                          src={playlist.cover_url || "/music-playlist.png"}
                          alt={playlist.name}
                          fill
                          className="object-cover"
                        />
                      </div>
                      <div className="flex-1">
                        <p className="font-medium text-foreground">{playlist.name}</p>
                        <p className="text-sm text-muted-foreground">{playlist.track_count || 0} titres</p>
                      </div>
                    </Link>
                  ))}
                </div>
              </section>
            )}

            {/* Top Tracks */}
            <section>
              <SectionHeader title="Titres Populaires" />
              <div className="mt-4 space-y-1">
                {playerTracks.length > 0 ? (
                  playerTracks.map((track: any, index: number) => {
                    const isCurrentTrack = currentTrack?.id === track.id
                    const trackIsPlaying = isCurrentTrack && isPlaying

                    return (
                      <button
                        key={track.id}
                        onClick={() => (isCurrentTrack ? togglePlay() : playTrack(track))}
                        className={`flex w-full items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary text-left ${isCurrentTrack ? "bg-secondary/50" : ""}`}
                      >
                        <span
                          className={`w-5 text-center text-sm ${isCurrentTrack ? "text-primary" : "text-muted-foreground"}`}
                        >
                          {trackIsPlaying ? (
                            <span className="flex justify-center gap-0.5">
                              <span className="h-3 w-0.5 animate-pulse bg-primary" />
                              <span
                                className="h-4 w-0.5 animate-pulse bg-primary"
                                style={{ animationDelay: "150ms" }}
                              />
                            </span>
                          ) : (
                            index + 1
                          )}
                        </span>
                        <div className="relative h-10 w-10 overflow-hidden rounded">
                          <Image
                            src={track.image || "/placeholder.svg"}
                            alt={track.title}
                            fill
                            className="object-cover"
                          />
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className={`truncate font-medium ${isCurrentTrack ? "text-primary" : "text-foreground"}`}>
                            {track.title}
                          </p>
                          <p className="truncate text-sm text-muted-foreground">{track.artist}</p>
                        </div>
                        <span className="text-sm text-muted-foreground">{formatDuration(track.duration * 1000)}</span>
                      </button>
                    )
                  })
                ) : (
                  <p className="text-center text-muted-foreground py-8">Aucun titre dans ce genre</p>
                )}
              </div>
            </section>
          </>
        )}
      </div>

      <BottomNav />
    </div>
  )
}
