"use client"

import Image from "next/image"
import Link from "next/link"
import { ChevronLeft, Play, Shuffle, Heart, MoreHorizontal, Download, Loader2 } from "lucide-react"
import { BottomNav } from "@/components/bottom-nav"
import { Button } from "@/components/ui/button"
import { usePlayer } from "@/components/player-provider"
import { useAuth } from "@/components/auth-provider"
import useSWR from "swr"

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

export default function LikedPage() {
  const { user } = useAuth()
  const {
    likedTracks,
    toggleLike,
    playTrack,
    playAlbum,
    currentTrack,
    isPlaying,
    togglePlay,
    toggleShuffle,
    shuffleEnabled,
  } = usePlayer()

  // Fetch user's liked tracks from database
  const { data: likedData, isLoading } = useSWR(user?.id ? `/api/users/${user.id}/liked-tracks` : null, fetcher)

  const likedSongs = likedData?.tracks || []

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

  const handlePlayAll = () => {
    if (likedSongs.length > 0) {
      const tracksToPlay = likedSongs.map((song: any) => ({
        id: song.id,
        title: song.title,
        artist: song.artist_name || "Unknown",
        image: song.cover_url || "/abstract-music-album.png",
        cover_url: song.cover_url,
        album_cover: song.album_cover,
        duration: (song.duration_ms || 0) / 1000,
        audioUrl: song.audio_url,
      }))
      playAlbum(tracksToPlay, 0)
    }
  }

  const handleShufflePlay = () => {
    if (likedSongs.length > 0) {
      if (!shuffleEnabled) toggleShuffle()
      handlePlayAll()
    }
  }

  const handlePlayTrack = (song: any) => {
    const track = {
      id: song.id,
      title: song.title,
      artist: song.artist_name || "Unknown",
      image: song.cover_url || "/abstract-music-album.png",
      cover_url: song.cover_url,
      album_cover: song.album_cover,
      duration: (song.duration_ms || 0) / 1000,
      audioUrl: song.audio_url,
    }
    if (currentTrack?.id === song.id) {
      togglePlay()
    } else {
      playTrack(track)
    }
  }

  return (
    <div className="min-h-screen bg-background pb-24">
      {/* Hero Section */}
      <div className="relative h-64 bg-gradient-to-b from-primary/30 to-background">
        <div className="absolute inset-0 flex items-center justify-center">
          <div className="grid h-40 w-40 grid-cols-2 gap-1 overflow-hidden rounded-lg shadow-2xl">
            {likedSongs.slice(0, 4).map((song: any, i: number) => (
              <div key={song.id} className="relative h-20 w-20">
                <Image
                  src={song.cover_url || "/placeholder.svg?height=80&width=80&query=music"}
                  alt={song.title}
                  fill
                  className="object-cover"
                />
              </div>
            ))}
            {likedSongs.length < 4 &&
              Array.from({ length: 4 - Math.min(likedSongs.length, 4) }).map((_, i) => (
                <div key={`empty-${i}`} className="h-20 w-20 bg-secondary" />
              ))}
          </div>
        </div>

        {/* 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>
      </div>

      {/* Info */}
      <div className="px-4 py-4">
        <h1 className="text-2xl font-bold text-foreground">Titres likes</h1>
        <p className="text-sm text-muted-foreground">{isLoading ? "Chargement..." : `${likedSongs.length} titres`}</p>
      </div>

      {/* Actions */}
      <div className="flex items-center justify-between px-4 pb-4">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" className="text-muted-foreground">
            <Download 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={handlePlayAll}>
          <Play className="h-6 w-6 fill-current" />
        </Button>
      </div>

      {/* Tracks */}
      <div className="px-4">
        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
          </div>
        ) : likedSongs.length === 0 ? (
          <div className="py-12 text-center">
            <Heart className="mx-auto h-12 w-12 text-muted-foreground mb-4" />
            <p className="text-muted-foreground">Aucun titre like</p>
            <Link href="/search" className="mt-2 inline-block text-primary hover:underline">
              Decouvrir de la musique
            </Link>
          </div>
        ) : (
          likedSongs.map((song: any) => {
            const isCurrentTrack = currentTrack?.id === song.id
            return (
              <div
                key={song.id}
                className={`flex items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary ${isCurrentTrack ? "bg-secondary/50" : ""}`}
              >
                <button onClick={() => handlePlayTrack(song)} className="relative flex items-center gap-3 flex-1">
                  <div className="relative h-12 w-12 overflow-hidden rounded">
                    <Image
                      src={song.cover_url || "/placeholder.svg?height=48&width=48&query=music"}
                      alt={song.title}
                      fill
                      className="object-cover"
                    />
                    {isCurrentTrack && isPlaying && (
                      <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 text-left">
                    <h3 className={`font-medium ${isCurrentTrack ? "text-primary" : "text-foreground"}`}>
                      {song.title}
                    </h3>
                    <p className="text-sm text-muted-foreground">{song.artist_name || "Unknown"}</p>
                  </div>
                </button>
                <span className="text-sm text-muted-foreground">{formatDuration(song.duration_ms || 0)}</span>
                <button onClick={() => toggleLike(song.id)} className="p-2 text-primary">
                  <Heart className="h-5 w-5 fill-current" />
                </button>
              </div>
            )
          })
        )}
      </div>

      <BottomNav />
    </div>
  )
}
