"use client"

import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import {
  ChevronDown,
  MoreHorizontal,
  Play,
  Pause,
  SkipBack,
  SkipForward,
  Shuffle,
  Repeat,
  Repeat1,
  ListMusic,
  AudioLines,
  Moon,
  Heart,
  Share2,
  Volume2,
  VolumeX,
  Mic2,
  PlusCircle,
  Clock,
} from "lucide-react"
import { Slider } from "@/components/ui/slider"
import { usePlayer } from "@/components/player-provider"
import { formatDuration } from "@/lib/music-data"
import { ShareModal } from "@/components/share-modal"
import { AddToPlaylistModal } from "@/components/add-to-playlist-modal"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"

export default function NowPlayingPage() {
  const {
    currentTrack,
    isPlaying,
    progress,
    volume,
    shuffleEnabled,
    repeatMode,
    sleepTimerRemaining,
    togglePlay,
    nextTrack,
    previousTrack,
    seekTo,
    setVolume,
    toggleShuffle,
    setRepeatMode,
    toggleLike,
    isLiked,
    addToQueue,
  } = usePlayer()

  const [showVolume, setShowVolume] = useState(false)
  const [shareOpen, setShareOpen] = useState(false)
  const [playlistOpen, setPlaylistOpen] = useState(false)
  const [imageError, setImageError] = useState(false)

  if (!currentTrack) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <p className="text-muted-foreground">Aucune piste en lecture</p>
      </div>
    )
  }

  const coverImage =
    currentTrack.cover_url || currentTrack.album_cover || currentTrack.image || "/placeholder.svg?height=500&width=500"

  console.log("[v0] Now Playing - Track image sources:", {
    cover_url: currentTrack.cover_url,
    album_cover: currentTrack.album_cover,
    image: currentTrack.image,
    finalCoverImage: coverImage,
  })

  const handleRepeatClick = () => {
    if (repeatMode === "off") setRepeatMode("all")
    else if (repeatMode === "all") setRepeatMode("one")
    else setRepeatMode("off")
  }

  const formatTimerRemaining = (seconds: number): string => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, "0")}`
  }

  const durationInSeconds = Math.floor((currentTrack.duration || 0) / 1000)
  const progressInSeconds = Math.floor(progress)

  return (
    <div className="min-h-screen bg-background">
      {/* Background blur */}
      <div className="fixed inset-0 -z-10">
        <Image
          src={coverImage || "/placeholder.svg"}
          alt=""
          fill
          className="object-cover opacity-20 blur-3xl"
          unoptimized
          onError={() => setImageError(true)}
        />
        <div className="absolute inset-0 bg-gradient-to-b from-background/50 to-background" />
      </div>

      <div className="mx-auto max-w-md px-4 py-6">
        {/* Header */}
        <div className="mb-8 flex items-center justify-between">
          <Link href="/" className="text-foreground hover:text-primary">
            <ChevronDown className="h-6 w-6" />
          </Link>
          <div className="text-center">
            <p className="text-xs text-muted-foreground uppercase tracking-wider">En lecture depuis</p>
            <p className="text-sm font-medium text-foreground">{currentTrack.album || "Ma Bibliothèque"}</p>
          </div>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button className="text-muted-foreground hover:text-foreground">
                <MoreHorizontal className="h-6 w-6" />
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-56">
              <DropdownMenuItem onClick={() => setPlaylistOpen(true)}>
                <PlusCircle className="mr-2 h-4 w-4" />
                Ajouter à une playlist
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => addToQueue(currentTrack)}>
                <ListMusic className="mr-2 h-4 w-4" />
                Ajouter à la file
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => setShareOpen(true)}>
                <Share2 className="mr-2 h-4 w-4" />
                Partager
              </DropdownMenuItem>
              <DropdownMenuItem asChild>
                <Link href={`/artist/${currentTrack.artistId || "1"}`}>Voir l'artiste</Link>
              </DropdownMenuItem>
              <DropdownMenuItem asChild>
                <Link href={`/album/${currentTrack.albumId || "1"}`}>Voir l'album</Link>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>

        {/* Album Art */}
        <div className="mb-8">
          <div className="relative mx-auto aspect-square w-full max-w-sm overflow-hidden rounded-2xl shadow-2xl">
            <img
              src={coverImage || "/placeholder.svg"}
              alt={currentTrack.title}
              className="h-full w-full object-cover"
              onError={(e) => {
                console.log("[v0] Cover image failed to load:", coverImage)
                setImageError(true)
                e.currentTarget.src = "/placeholder.svg?height=500&width=500"
              }}
              onLoad={() => console.log("[v0] Cover image loaded successfully:", coverImage)}
            />
          </div>
        </div>

        {/* Track Info & Actions */}
        <div className="mb-6 flex items-start justify-between">
          <div className="flex-1 min-w-0">
            <h2 className="text-2xl font-bold text-foreground truncate">{currentTrack.title}</h2>
            {currentTrack.artistId ? (
              <Link
                href={`/artist/${currentTrack.artistId}`}
                className="text-muted-foreground hover:text-primary hover:underline inline-block"
              >
                {currentTrack.artist}
              </Link>
            ) : (
              <p className="text-muted-foreground">{currentTrack.artist}</p>
            )}
          </div>
          <div className="flex items-center gap-1">
            <button
              onClick={() => toggleLike(currentTrack.id)}
              className={`p-2 ${isLiked(currentTrack.id) ? "text-primary" : "text-muted-foreground hover:text-foreground"}`}
            >
              <Heart className={`h-6 w-6 ${isLiked(currentTrack.id) ? "fill-current" : ""}`} />
            </button>
          </div>
        </div>

        {/* Progress Bar */}
        <div className="mb-6 space-y-2">
          <Slider
            value={[progressInSeconds]}
            max={durationInSeconds}
            step={1}
            onValueChange={(value) => seekTo(value[0])}
            className="w-full"
          />
          <div className="flex justify-between text-sm text-muted-foreground">
            <span>{formatDuration(progressInSeconds)}</span>
            <span>{formatDuration(durationInSeconds)}</span>
          </div>
        </div>

        {/* Playback Controls */}
        <div className="mb-8 flex items-center justify-center gap-6">
          <button
            onClick={toggleShuffle}
            className={`transition-colors ${shuffleEnabled ? "text-primary" : "text-muted-foreground hover:text-foreground"}`}
          >
            <Shuffle className="h-5 w-5" />
          </button>
          <button onClick={previousTrack} className="text-foreground hover:text-primary">
            <SkipBack className="h-8 w-8" />
          </button>
          <button
            onClick={togglePlay}
            className="flex h-16 w-16 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-transform hover:scale-105"
          >
            {isPlaying ? <Pause className="h-8 w-8" /> : <Play className="ml-1 h-8 w-8" />}
          </button>
          <button onClick={nextTrack} className="text-foreground hover:text-primary">
            <SkipForward className="h-8 w-8" />
          </button>
          <button
            onClick={handleRepeatClick}
            className={`transition-colors ${repeatMode !== "off" ? "text-primary" : "text-muted-foreground hover:text-foreground"}`}
          >
            {repeatMode === "one" ? <Repeat1 className="h-5 w-5" /> : <Repeat className="h-5 w-5" />}
          </button>
        </div>

        {/* Volume Control */}
        <div className="mb-6">
          <div className="flex items-center gap-4">
            <button onClick={() => setShowVolume(!showVolume)} className="text-muted-foreground hover:text-foreground">
              {volume === 0 ? <VolumeX className="h-5 w-5" /> : <Volume2 className="h-5 w-5" />}
            </button>
            {showVolume && (
              <Slider
                value={[volume]}
                max={100}
                step={1}
                onValueChange={(value) => setVolume(value[0])}
                className="flex-1"
              />
            )}
            {showVolume && <span className="text-sm text-muted-foreground w-8">{volume}%</span>}
          </div>
        </div>

        {/* Sleep Timer Indicator */}
        {sleepTimerRemaining !== null && sleepTimerRemaining > 0 && (
          <Link
            href="/sleep-timer"
            className="mb-6 flex items-center justify-center gap-2 rounded-full bg-secondary/80 px-4 py-2 text-sm"
          >
            <Clock className="h-4 w-4 text-primary" />
            <span className="text-muted-foreground">Arrêt dans {formatTimerRemaining(sleepTimerRemaining)}</span>
          </Link>
        )}

        {/* Additional Controls */}
        <div className="flex items-center justify-center gap-6">
          <Link href="/lyrics" className="flex flex-col items-center gap-1 text-muted-foreground hover:text-primary">
            <Mic2 className="h-6 w-6" />
            <span className="text-xs">Paroles</span>
          </Link>
          <Link href="/queue" className="flex flex-col items-center gap-1 text-muted-foreground hover:text-primary">
            <ListMusic className="h-6 w-6" />
            <span className="text-xs">File</span>
          </Link>
          <Link href="/equalizer" className="flex flex-col items-center gap-1 text-muted-foreground hover:text-primary">
            <AudioLines className="h-6 w-6" />
            <span className="text-xs">Égaliseur</span>
          </Link>
          <Link
            href="/sleep-timer"
            className={`flex flex-col items-center gap-1 ${sleepTimerRemaining ? "text-primary" : "text-muted-foreground hover:text-primary"}`}
          >
            <Moon className="h-6 w-6" />
            <span className="text-xs">Minuterie</span>
          </Link>
        </div>
      </div>

      <ShareModal
        open={shareOpen}
        onOpenChange={setShareOpen}
        title={currentTrack.title}
        artist={currentTrack.artist}
        type="track"
      />

      <AddToPlaylistModal open={playlistOpen} onOpenChange={setPlaylistOpen} track={currentTrack} />
    </div>
  )
}
