"use client"

import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { useParams } from "next/navigation"
import { ChevronLeft, Play, Pause, Shuffle, RefreshCw, Heart, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { BottomNav } from "@/components/bottom-nav"
import { usePlayer } from "@/components/player-provider"
import { formatDuration } from "@/lib/music-data"
import useSWR from "swr"

interface Track {
  id: string
  title: string
  artist: string
  artist_name?: string
  image?: string
  cover_url?: string
  duration: number
  audio_url?: string
  audioUrl?: string
}

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

export default function RadioPage() {
  const { id } = useParams()
  const radioId = Array.isArray(id) ? id[0] : id
  const [refreshKey, setRefreshKey] = useState(0)

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

  const { data: seedTrackData, isLoading: seedLoading } = useSWR(radioId ? `/api/tracks/${radioId}` : null, fetcher, {
    dedupingInterval: 60000,
  })

  const {
    data: tracksData,
    isLoading: tracksLoading,
    mutate,
  } = useSWR(`/api/tracks?limit=25&status=published&random=true&key=${refreshKey}`, fetcher, {
    dedupingInterval: 10000,
  })

  const seedTrack: Track | null = seedTrackData?.data
    ? {
        id: seedTrackData.data.id,
        title: seedTrackData.data.title,
        artist: seedTrackData.data.artist_name || "Unknown",
        image: seedTrackData.data.cover_url || "/placeholder.svg",
        duration: seedTrackData.data.duration || 0,
        audioUrl: seedTrackData.data.audio_url,
      }
    : null

  const radioTracks: Track[] = (tracksData?.data || []).map((t: any) => ({
    id: t.id,
    title: t.title,
    artist: t.artist_name || t.artist || "Unknown",
    image: t.cover_url || "/placeholder.svg",
    duration: t.duration || 0,
    audioUrl: t.audio_url,
  }))

  const isRadioPlaying = radioTracks.some((t) => t.id === currentTrack?.id) && isPlaying
  const isLoading = seedLoading || tracksLoading

  const handlePlayRadio = () => {
    if (isRadioPlaying) {
      togglePlay()
    } else if (radioTracks.length > 0) {
      playAlbum(radioTracks, 0)
    }
  }

  const handleRefresh = () => {
    setRefreshKey((prev) => prev + 1)
    mutate()
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    )
  }

  const displayTrack = seedTrack || (radioTracks.length > 0 ? radioTracks[0] : null)

  return (
    <div className="min-h-screen bg-background pb-24">
      {/* Header */}
      <div className="relative h-64 overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-br from-purple-600 via-pink-500 to-orange-400" />
        <div className="absolute inset-0 bg-gradient-to-t from-background to-transparent" />

        <div className="absolute left-0 right-0 top-0 z-10 flex items-center justify-between p-4">
          <Link href="/" className="rounded-full bg-black/30 p-2 text-white hover:bg-black/50">
            <ChevronLeft className="h-5 w-5" />
          </Link>
        </div>

        <div className="absolute bottom-6 left-0 right-0 px-4">
          <p className="text-white/80 text-xs uppercase tracking-wider mb-1">Radio basée sur</p>
          <h1 className="text-2xl font-bold text-white mb-1">{displayTrack?.title || "Radio"}</h1>
          <p className="text-white/80 text-sm mb-4">Musique similaire sélectionnée pour vous</p>

          <div className="flex items-center gap-3">
            <Button
              size="icon"
              className="h-12 w-12 rounded-full"
              onClick={handlePlayRadio}
              disabled={radioTracks.length === 0}
            >
              {isRadioPlaying ? <Pause className="h-6 w-6" /> : <Play className="h-6 w-6 ml-0.5" />}
            </Button>
            <Button
              variant="outline"
              size="icon"
              className="rounded-full border-white/50 bg-white/10 text-white hover:bg-white/20"
              onClick={toggleShuffle}
            >
              <Shuffle className={`h-5 w-5 ${shuffleEnabled ? "text-primary" : ""}`} />
            </Button>
            <Button
              variant="outline"
              size="icon"
              className="rounded-full border-white/50 bg-white/10 text-white hover:bg-white/20"
              onClick={handleRefresh}
            >
              <RefreshCw className="h-5 w-5" />
            </Button>
          </div>
        </div>
      </div>

      {/* Track List */}
      <div className="mx-auto max-w-md px-4 py-6">
        <p className="text-sm text-muted-foreground mb-4">{radioTracks.length} titres</p>

        {radioTracks.length === 0 ? (
          <div className="text-center py-12 text-muted-foreground">Aucun titre disponible pour la radio</div>
        ) : (
          <div className="space-y-1">
            {radioTracks.map((track, index) => {
              const isCurrentTrack = currentTrack?.id === track.id
              const trackIsPlaying = isCurrentTrack && isPlaying

              return (
                <button
                  key={`${track.id}-${index}`}
                  onClick={() => (isCurrentTrack ? togglePlay() : playTrack({ ...track, audioUrl: track.audioUrl }))}
                  className={`flex w-full items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary text-left ${isCurrentTrack ? "bg-secondary/50" : ""}`}
                >
                  <span
                    className={`w-5 text-center text-sm ${isCurrentTrack ? "text-primary" : "text-muted-foreground"}`}
                  >
                    {trackIsPlaying ? (
                      <span className="flex justify-center 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>
                    ) : (
                      index + 1
                    )}
                  </span>
                  <div className="relative h-10 w-10 overflow-hidden rounded">
                    <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 ${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)}</span>
                </button>
              )
            })}
          </div>
        )}
      </div>

      <BottomNav />
    </div>
  )
}
