"use client"

import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { useParams } from "next/navigation"
import { ChevronLeft, MoreHorizontal, Play, Pause, Shuffle, RefreshCw, Heart, Loader2, Music } from "lucide-react"
import { Button } from "@/components/ui/button"
import { BottomNav } from "@/components/bottom-nav"
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")}`
}

function ImageWithFallback({
  src,
  alt,
  fill,
  className,
}: {
  src: string | null | undefined
  alt: string
  fill?: boolean
  className?: string
}) {
  const [error, setError] = useState(false)
  const validSrc = src && src.trim() !== "" && !error

  if (!validSrc || fill === false) {
    return (
      <div
        className={`bg-gradient-to-br from-purple-500/20 to-pink-500/20 flex items-center justify-center ${fill ? "absolute inset-0" : "w-full h-full"} ${className}`}
      >
        <Music className="h-12 w-12 text-purple-400/50" />
      </div>
    )
  }

  if (fill) {
    return (
      <img
        src={src || "/placeholder.svg"}
        alt={alt}
        className={`absolute inset-0 w-full h-full ${className}`}
        onError={() => setError(true)}
      />
    )
  }

  return <img src={src || "/placeholder.svg"} alt={alt} className={className} onError={() => setError(true)} />
}

export default function MixPage() {
  const { id } = useParams<{ id: string }>()
  const [isRefreshing, setIsRefreshing] = useState(false)

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

  const {
    data: tracksData,
    isLoading: tracksLoading,
    mutate,
    error: tracksError,
  } = useSWR(`/api/playlists/${id}/tracks`, fetcher, {
    revalidateOnFocus: false,
    shouldRetryOnError: false,
  })

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

  const playlist = playlistData?.data
  const mix = {
    title: playlist?.name || "Mix Personnalisé",
    description: playlist?.description || "Créé pour vous",
    image: playlist?.cover_url || null,
  }

  const tracks = tracksData?.data || []

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

  const isMixPlaying = playerTracks.some((t: any) => t.id === currentTrack?.id) && isPlaying
  const totalDuration = playerTracks.reduce((acc: number, t: any) => acc + t.duration, 0)
  const isLoading = playlistLoading || tracksLoading
  const hasError = playlistError || tracksError

  if (!isLoading && (hasError || !playlist)) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center p-4">
        <div className="text-center">
          <p className="text-muted-foreground mb-4 text-lg">Playlist non trouvée</p>
          <Link href="/library">
            <Button>Retour à la bibliothèque</Button>
          </Link>
        </div>
      </div>
    )
  }

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

  const handleRefresh = () => {
    setIsRefreshing(true)
    mutate().finally(() => {
      setTimeout(() => setIsRefreshing(false), 500)
    })
  }

  return (
    <div className="min-h-screen bg-background pb-24">
      {/* Hero Section */}
      <div className="relative">
        <div className="absolute inset-0 h-72 overflow-hidden">
          {mix.image ? (
            <>
              <Image
                src={mix.image || "/placeholder.svg"}
                alt="Mix Art"
                fill
                className="object-cover opacity-40 blur-xl"
              />
              <div className="absolute inset-0 bg-gradient-to-b from-transparent to-background" />
            </>
          ) : (
            <div className="absolute inset-0 bg-gradient-to-b from-purple-900/30 to-background" />
          )}
        </div>

        {/* Header */}
        <div className="relative z-10 flex items-center justify-between p-4">
          <Link href="/home" className="text-foreground hover:text-primary">
            <ChevronLeft className="h-6 w-6" />
          </Link>
          <button className="text-foreground hover:text-primary">
            <MoreHorizontal className="h-6 w-6" />
          </button>
        </div>

        {/* Mix Info */}
        <div className="relative z-10 flex flex-col items-center px-4 pb-6 pt-4">
          <div className="relative mb-4 h-40 w-40 overflow-hidden rounded-xl shadow-2xl bg-secondary">
            <ImageWithFallback src={mix.image || "/placeholder.svg"} alt={mix.title} fill className="object-cover" />
          </div>
          <h1 className="mb-1 text-xl font-bold text-foreground">{mix.title}</h1>
          <p className="mb-1 text-sm text-muted-foreground">{mix.description}</p>
          <p className="text-sm text-muted-foreground">
            {playerTracks.length} titres • {Math.floor(totalDuration / 60)} min
          </p>
        </div>
      </div>

      <div className="mx-auto max-w-md px-4">
        {/* Action Buttons */}
        <div className="mb-6 flex items-center justify-between">
          <button
            onClick={handleRefresh}
            className={`flex items-center gap-2 text-sm text-muted-foreground hover:text-primary ${isRefreshing ? "animate-spin" : ""}`}
          >
            <RefreshCw className="h-5 w-5" />
            Actualiser
          </button>
          <div className="flex items-center gap-3">
            <button
              onClick={toggleShuffle}
              className={`transition-colors ${shuffleEnabled ? "text-primary" : "text-muted-foreground hover:text-foreground"}`}
            >
              <Shuffle className="h-6 w-6" />
            </button>
            <Button
              size="icon"
              className="h-12 w-12 rounded-full"
              onClick={handlePlayMix}
              disabled={playerTracks.length === 0}
            >
              {isMixPlaying ? <Pause className="h-6 w-6" /> : <Play className="h-6 w-6 ml-0.5" />}
            </Button>
          </div>
        </div>

        {/* Track List */}
        {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 ? (
          <div className="space-y-1">
            {playerTracks.map((track: any) => {
              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" : ""}`}
                >
                  <div className="relative h-12 w-12 flex-shrink-0 overflow-hidden rounded-lg bg-secondary">
                    <ImageWithFallback
                      src={track.image || "/placeholder.svg"}
                      alt={track.title}
                      fill
                      className="object-cover"
                    />
                    {trackIsPlaying && (
                      <div className="absolute inset-0 flex items-center justify-center bg-black/50">
                        <div className="flex gap-0.5">
                          <span className="h-3 w-0.5 animate-pulse bg-white" />
                          <span className="h-4 w-0.5 animate-pulse bg-white" style={{ animationDelay: "150ms" }} />
                          <span className="h-2 w-0.5 animate-pulse bg-white" style={{ animationDelay: "300ms" }} />
                        </div>
                      </div>
                    )}
                  </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>
                  <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>
              )
            })}
          </div>
        ) : (
          <p className="text-center text-muted-foreground py-8">Aucun titre disponible</p>
        )}

        {/* Mix Info */}
        <div className="mt-8 rounded-xl bg-secondary/50 p-4">
          <h3 className="mb-2 font-medium text-foreground">À propos de ce mix</h3>
          <p className="text-sm text-muted-foreground">
            Ce mix est créé spécialement pour vous, basé sur vos artistes et genres préférés. Il est mis à jour chaque
            jour avec de nouvelles découvertes.
          </p>
        </div>
      </div>

      <BottomNav />
    </div>
  )
}
