"use client"

import Image from "next/image"
import Link from "next/link"
import { useParams } from "next/navigation"
import { ChevronLeft, Play, Pause, Shuffle, Heart, MoreHorizontal, Loader2 } from "lucide-react"
import { BottomNav } from "@/components/bottom-nav"
import { Button } from "@/components/ui/button"
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 moodColors: Record<string, string> = {
  "1": "from-amber-600 to-amber-900",
  "2": "from-red-600 to-red-900",
  "3": "from-yellow-600 to-yellow-900",
  "4": "from-violet-600 to-violet-900",
  dance: "from-amber-600 to-amber-900",
  chill: "from-blue-600 to-cyan-800",
  workout: "from-red-600 to-orange-700",
  focus: "from-purple-600 to-indigo-800",
  party: "from-pink-600 to-rose-700",
  default: "from-gray-600 to-gray-800",
}

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

  const { data: playlistData, isLoading: playlistLoading } = useSWR(`/api/playlists/${id}`, fetcher)

  const { data: tracksData, isLoading: tracksLoading } = useSWR(`/api/playlists/${id}/tracks`, fetcher)

  const {
    playTrack,
    playAlbum,
    currentTrack,
    isPlaying,
    togglePlay,
    toggleLike,
    isLiked,
    shuffleEnabled,
    toggleShuffle,
  } = usePlayer()

  const playlist = playlistData?.playlist || { name: "Playlist", description: "" }
  const tracks = tracksData?.tracks || []

  const moodColor = moodColors[id] || moodColors.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 isMoodPlaying = playerTracks.some((t: any) => t.id === currentTrack?.id) && isPlaying
  const totalDuration = playerTracks.reduce((acc: number, t: any) => acc + t.duration, 0)

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

  const handleShufflePlay = () => {
    if (!shuffleEnabled) toggleShuffle()
    if (playerTracks.length > 0) {
      playAlbum(playerTracks, 0)
    }
  }

  const isLoading = playlistLoading || tracksLoading

  return (
    <div className="min-h-screen bg-background pb-24">
      {/* Hero Section */}
      <div className={`relative h-72 bg-gradient-to-b ${moodColor}`}>
        <Image
          src={playlist.cover_url || "/placeholder.svg?height=400&width=400&query=music playlist mood"}
          alt={playlist.name}
          fill
          className="object-cover opacity-50"
        />
        <div className="absolute inset-0 bg-gradient-to-b from-transparent to-background" />

        {/* Header */}
        <div className="absolute top-0 left-0 right-0 flex items-center justify-between p-4">
          <Link href="/library" className="rounded-full bg-black/30 p-2 text-white">
            <ChevronLeft className="h-5 w-5" />
          </Link>
          <button className="rounded-full bg-black/30 p-2 text-white">
            <MoreHorizontal className="h-5 w-5" />
          </button>
        </div>

        {/* Title */}
        <div className="absolute bottom-4 left-4 right-4">
          <h1 className="text-2xl font-bold text-white">{playlist.name}</h1>
          <p className="text-sm text-white/80">{playlist.description || "Playlist personnalisée"}</p>
          <p className="mt-1 text-xs text-white/60">
            {playerTracks.length} titres • {Math.floor(totalDuration / 60)} min
          </p>
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center justify-between px-4 py-4">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" className="text-muted-foreground">
            <Heart className="h-6 w-6" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className={shuffleEnabled ? "text-primary" : "text-muted-foreground"}
            onClick={handleShufflePlay}
          >
            <Shuffle className="h-6 w-6" />
          </Button>
        </div>
        <Button
          size="icon"
          className="h-14 w-14 rounded-full bg-primary"
          onClick={handlePlayMood}
          disabled={playerTracks.length === 0}
        >
          {isMoodPlaying ? <Pause className="h-6 w-6" /> : <Play className="h-6 w-6 fill-current" />}
        </Button>
      </div>

      {/* Tracks */}
      <div className="px-4">
        {isLoading ? (
          <div className="flex items-center justify-center py-16">
            <Loader2 className="w-8 h-8 animate-spin text-purple-500" />
          </div>
        ) : 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-6 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-12 w-12 overflow-hidden rounded">
                  <Image src={track.image || "/placeholder.svg"} alt={track.title} fill className="object-cover" />
                </div>
                <div className="flex-1">
                  <h3 className={`font-medium ${isCurrentTrack ? "text-primary" : "text-foreground"}`}>
                    {track.title}
                  </h3>
                  <p className="text-sm text-muted-foreground">{track.artist}</p>
                </div>
                <button
                  onClick={(e) => {
                    e.stopPropagation()
                    toggleLike(track.id)
                  }}
                  className={`p-1 ${isLiked(track.id) ? "text-primary" : "text-muted-foreground"}`}
                >
                  <Heart className={`h-4 w-4 ${isLiked(track.id) ? "fill-current" : ""}`} />
                </button>
                <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 cette playlist</p>
        )}
      </div>

      <BottomNav />
    </div>
  )
}
