"use client"

import Image from "next/image"
import Link from "next/link"
import { ChevronLeft, GripVertical, X, Shuffle, Repeat, Repeat1, Plus, Loader2 } from "lucide-react"
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")}`
}

export default function QueuePage() {
  const {
    currentTrack,
    isPlaying,
    queue,
    queueIndex,
    shuffleEnabled,
    repeatMode,
    toggleShuffle,
    setRepeatMode,
    removeFromQueue,
    addToQueue,
    playTrack,
  } = usePlayer()

  const { data: suggestionsData, isLoading: suggestionsLoading } = useSWR(
    "/api/tracks?status=published&limit=5",
    fetcher,
  )

  const upNext = queue.slice(queueIndex + 1)
  const history = queue.slice(0, queueIndex)

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

  const suggestions = (suggestionsData?.data || [])
    .filter((t: any) => !queue.some((q) => q.id === t.id))
    .slice(0, 3)
    .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,
    }))

  return (
    <div className="min-h-screen bg-background pb-24">
      <div className="mx-auto max-w-md px-4 py-6">
        {/* Header */}
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Link href="/now-playing" className="text-foreground hover:text-primary">
              <ChevronLeft className="h-6 w-6" />
            </Link>
            <h1 className="text-xl font-bold text-foreground">File d{"'"}attente</h1>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={toggleShuffle}
              className={`rounded-lg p-2 transition-colors ${shuffleEnabled ? "text-primary" : "text-muted-foreground hover:text-foreground"}`}
            >
              <Shuffle className="h-5 w-5" />
            </button>
            <button
              onClick={handleRepeatClick}
              className={`relative rounded-lg p-2 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>
        </div>

        {/* Now Playing */}
        {currentTrack && (
          <section className="mb-8">
            <h2 className="mb-3 text-sm font-semibold uppercase text-muted-foreground">En cours de lecture</h2>
            <div className="flex items-center gap-3 rounded-xl bg-primary/10 p-3">
              <div className="relative h-14 w-14 flex-shrink-0 overflow-hidden rounded-lg">
                <Image
                  src={currentTrack.image || "/placeholder.svg"}
                  alt={currentTrack.title}
                  fill
                  className="object-cover"
                />
                {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" />
                      <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>
                )}
              </div>
              <div className="flex-1 min-w-0">
                <p className="truncate font-medium text-primary">{currentTrack.title}</p>
                <p className="truncate text-sm text-muted-foreground">{currentTrack.artist}</p>
              </div>
              <span className="text-sm text-muted-foreground">{formatDuration(currentTrack.duration * 1000)}</span>
            </div>
          </section>
        )}

        {/* Up Next */}
        <section className="mb-8">
          <h2 className="mb-3 text-sm font-semibold uppercase text-muted-foreground">À suivre ({upNext.length})</h2>
          {upNext.length > 0 ? (
            <div className="space-y-1">
              {upNext.map((track, index) => (
                <div
                  key={`${track.id}-${index}`}
                  className="flex items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary group"
                >
                  <button className="cursor-grab text-muted-foreground opacity-0 group-hover:opacity-100">
                    <GripVertical className="h-5 w-5" />
                  </button>
                  <button
                    onClick={() => playTrack(track)}
                    className="relative h-12 w-12 flex-shrink-0 overflow-hidden rounded-lg"
                  >
                    <Image src={track.image || "/placeholder.svg"} alt={track.title} fill className="object-cover" />
                  </button>
                  <div className="flex-1 min-w-0">
                    <p className="truncate font-medium text-foreground">{track.title}</p>
                    <p className="truncate text-sm text-muted-foreground">{track.artist}</p>
                  </div>
                  <span className="text-sm text-muted-foreground">{formatDuration(track.duration * 1000)}</span>
                  <button
                    onClick={() => removeFromQueue(queueIndex + 1 + index)}
                    className="text-muted-foreground opacity-0 group-hover:opacity-100 hover:text-destructive"
                  >
                    <X className="h-5 w-5" />
                  </button>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-center text-muted-foreground py-4">Aucun titre à suivre</p>
          )}
        </section>

        {/* Suggestions */}
        <section className="mb-8">
          <h2 className="mb-3 text-sm font-semibold uppercase text-muted-foreground">Suggestions</h2>
          {suggestionsLoading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="w-6 h-6 animate-spin text-purple-500" />
            </div>
          ) : suggestions.length > 0 ? (
            <div className="space-y-1">
              {suggestions.map((track: any) => (
                <div
                  key={track.id}
                  className="flex items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary group"
                >
                  <div className="relative h-12 w-12 flex-shrink-0 overflow-hidden rounded-lg">
                    <Image src={track.image || "/placeholder.svg"} alt={track.title} fill className="object-cover" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="truncate font-medium text-foreground">{track.title}</p>
                    <p className="truncate text-sm text-muted-foreground">{track.artist}</p>
                  </div>
                  <button
                    onClick={() => addToQueue(track)}
                    className="flex items-center gap-1 rounded-full bg-secondary px-3 py-1 text-sm text-foreground hover:bg-primary hover:text-primary-foreground"
                  >
                    <Plus className="h-4 w-4" />
                    Ajouter
                  </button>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-center text-muted-foreground py-4">Aucune suggestion disponible</p>
          )}
        </section>

        {/* History */}
        {history.length > 0 && (
          <section>
            <h2 className="mb-3 text-sm font-semibold uppercase text-muted-foreground">Historique</h2>
            <div className="space-y-1 opacity-60">
              {history.map((track, index) => (
                <div
                  key={`history-${track.id}-${index}`}
                  className="flex items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary"
                >
                  <div className="relative h-10 w-10 flex-shrink-0 overflow-hidden rounded-lg">
                    <Image src={track.image || "/placeholder.svg"} alt={track.title} fill className="object-cover" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="truncate text-sm font-medium text-foreground">{track.title}</p>
                    <p className="truncate text-xs text-muted-foreground">{track.artist}</p>
                  </div>
                </div>
              ))}
            </div>
          </section>
        )}
      </div>

      <BottomNav />
    </div>
  )
}
