"use client"

import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { usePathname, useRouter } from "next/navigation"
import { Play, Pause, SkipForward, Heart, X, ChevronUp, WifiOff, Square, Loader2 } from "lucide-react"
import { usePlayer } from "./player-provider"
import { getImageUrl } from "@/lib/image-utils"

const AUTH_PAGES = ["/", "/signup", "/forgot-password", "/welcome"]

export function GlobalMiniPlayer() {
  const pathname = usePathname()
  const router = useRouter()
  const {
    currentTrack,
    isPlaying,
    togglePlay,
    nextTrack,
    progress,
    toggleLike,
    isLiked,
    isPlayerVisible,
    hidePlayer,
    showPlayer,
    isOfflineMode,
    isDownloaded,
    stopPlayback,
    isLoading,
  } = usePlayer()
  const [imageError, setImageError] = useState(false)

  const isAuthPage = AUTH_PAGES.includes(pathname)
  const isAdminPage = pathname.startsWith("/admin")

  if (isAuthPage || pathname === "/now-playing" || isAdminPage || !currentTrack) {
    return null
  }

  const progressPercent = currentTrack.duration > 0 ? (progress / currentTrack.duration) * 100 : 0
  const isCurrentTrackOffline = isDownloaded(currentTrack.id)

  if (!isPlayerVisible) {
    return (
      <button
        onClick={showPlayer}
        className="fixed bottom-20 right-4 z-40 flex items-center gap-2 rounded-full bg-primary px-4 py-2 text-primary-foreground shadow-lg"
      >
        <ChevronUp className="h-4 w-4" />
        <span className="text-sm font-medium">Lecture en cours</span>
        {isPlaying && (
          <div className="flex gap-0.5">
            <span className="h-2 w-0.5 animate-pulse bg-primary-foreground" />
            <span className="h-3 w-0.5 animate-pulse bg-primary-foreground" style={{ animationDelay: "150ms" }} />
            <span className="h-2 w-0.5 animate-pulse bg-primary-foreground" style={{ animationDelay: "300ms" }} />
          </div>
        )}
      </button>
    )
  }

  return (
    <div className="fixed bottom-16 left-0 right-0 z-40 border-t border-border bg-secondary/95 backdrop-blur-lg">
      <div className="mx-auto max-w-md">
        {/* Progress bar */}
        <div className="h-1 w-full bg-muted">
          <div
            className="h-full bg-primary transition-all duration-1000 ease-linear"
            style={{ width: `${progressPercent}%` }}
          />
        </div>

        <div className="flex items-center gap-3 p-2">
          <button
            onClick={hidePlayer}
            className="p-1 text-muted-foreground hover:text-foreground"
            aria-label="Minimiser le lecteur"
          >
            <X className="h-4 w-4" />
          </button>

          <div 
            onClick={() => router.push("/now-playing")} 
            className="flex flex-1 items-center gap-3 cursor-pointer"
            role="button"
            tabIndex={0}
            onKeyDown={(e) => e.key === "Enter" && router.push("/now-playing")}
          >
            <div className="relative h-12 w-12 flex-shrink-0 overflow-hidden rounded-lg bg-secondary">
              {!imageError && (currentTrack.cover_url || currentTrack.album_cover || currentTrack.image) ? (
                <Image
                  src={getImageUrl(currentTrack.cover_url || currentTrack.album_cover || currentTrack.image, "track")}
                  alt={currentTrack.title}
                  fill
                  className="object-cover"
                  onError={() => setImageError(true)}
                />
              ) : (
                <div className="flex h-full w-full items-center justify-center bg-gradient-to-br from-primary/20 to-primary/5">
                  <span className="text-lg">🎵</span>
                </div>
              )}
              {isLoading ? (
                <div className="absolute inset-0 flex items-center justify-center bg-black/30">
                  <Loader2 className="h-5 w-5 animate-spin text-primary" />
                </div>
              ) : isPlaying ? (
                <div className="absolute inset-0 flex items-center justify-center bg-black/30">
                  <div className="flex gap-0.5">
                    <span className="h-3 w-0.5 animate-pulse bg-primary" style={{ animationDelay: "0ms" }} />
                    <span className="h-4 w-0.5 animate-pulse bg-primary" style={{ animationDelay: "150ms" }} />
                    <span className="h-2 w-0.5 animate-pulse bg-primary" style={{ animationDelay: "300ms" }} />
                  </div>
                </div>
              ) : null}
              {isCurrentTrackOffline && (
                <div className="absolute bottom-0.5 right-0.5 rounded-full bg-primary p-0.5">
                  <WifiOff className="h-2 w-2 text-primary-foreground" />
                </div>
              )}
            </div>
            <div className="min-w-0 flex-1">
              <div className="flex items-center gap-1">
                <p className="truncate text-sm font-medium text-foreground">{currentTrack.title}</p>
                {isOfflineMode && !isCurrentTrackOffline && (
                  <WifiOff className="h-3 w-3 text-destructive flex-shrink-0" />
                )}
              </div>
              {currentTrack.artistId ? (
                <Link 
                  href={`/artist/${currentTrack.artistId}`} 
                  onClick={(e) => e.stopPropagation()} 
                  className="block"
                >
                  <p className="truncate text-xs text-muted-foreground hover:text-primary hover:underline">
                    {currentTrack.artist}
                  </p>
                </Link>
              ) : (
                <p className="truncate text-xs text-muted-foreground">{currentTrack.artist}</p>
              )}
            </div>
          </div>

          <div className="flex items-center gap-1">
            <button
              onClick={() => toggleLike(currentTrack.id)}
              className={`p-2 ${isLiked(currentTrack.id) ? "text-primary" : "text-muted-foreground"}`}
            >
              <Heart className={`h-5 w-5 ${isLiked(currentTrack.id) ? "fill-current" : ""}`} />
            </button>
            <button
              onClick={stopPlayback}
              className="p-2 text-muted-foreground hover:text-destructive"
              aria-label="Arrêter la lecture"
            >
              <Square className="h-4 w-4 fill-current" />
            </button>
            <button
              onClick={togglePlay}
              disabled={isLoading}
              className="flex h-9 w-9 items-center justify-center rounded-full bg-foreground text-background disabled:opacity-50"
            >
              {isLoading ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : isPlaying ? (
                <Pause className="h-4 w-4" />
              ) : (
                <Play className="h-4 w-4 ml-0.5" />
              )}
            </button>
            <button onClick={nextTrack} className="p-2 text-foreground">
              <SkipForward className="h-5 w-5" />
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
