"use client"

import type React from "react"

import { DropdownMenuSeparator } from "@/components/ui/dropdown-menu"

import { useState } from "react"
import useSWR from "swr"
import {
  Search,
  MoreVertical,
  Play,
  Pause,
  Edit,
  Trash2,
  Eye,
  Upload,
  ChevronLeft,
  ChevronRight,
  Download,
  Check,
  Loader2,
  X,
  Plus,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { ConfirmDialog } from "@/components/confirm-dialog"
import { usePlayer } from "@/components/player-provider"
import { useRouter } from "next/navigation"
import { useToast } from "@/hooks/use-toast"

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

interface Track {
  id: string
  title: string
  artist_id: string
  artist_name?: string
  album_id: string | null
  album_title?: string
  duration_ms: number
  total_streams: number
  status: string
  cover_url: string | null
  audio_url: string
}

export default function AdminTracksPage() {
  const { data: tracksData, isLoading, mutate } = useSWR("/api/tracks?limit=100", fetcher)
  const { data: genresData } = useSWR("/api/genres", fetcher)
  const { playTrack, currentTrack, isPlaying, togglePlay } = usePlayer()
  const router = useRouter()
  const { toast } = useToast()

  const tracks: Track[] = tracksData?.data || []
  const genres: string[] = genresData?.data?.map((g: any) => g.name) || ["Pop", "Rock", "Hip-Hop", "Electronic", "Jazz"]

  const [searchQuery, setSearchQuery] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [genreFilter, setGenreFilter] = useState("all")
  const [showAddTrack, setShowAddTrack] = useState(false)
  const [showEditTrack, setShowEditTrack] = useState<Track | null>(null)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(null)
  const [currentPage, setCurrentPage] = useState(1)
  const tracksPerPage = 10
  const [isRecalculating, setIsRecalculating] = useState(false)
  const [audioFile, setAudioFile] = useState<File | null>(null)
  const [isUploading, setIsUploading] = useState(false)

  // Form state
  const [formData, setFormData] = useState({
    title: "",
    artist_id: "",
    album_id: "",
    genre_id: "",
    duration: "3:30",
    status: "draft" as "published" | "draft" | "pending",
  })

  const showToast = (message: string, type = "success") => {
    toast({ message, type })
  }

  const filteredTracks = tracks.filter((track) => {
    const matchesSearch =
      track.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (track.artist_name || "").toLowerCase().includes(searchQuery.toLowerCase())
    const matchesStatus = statusFilter === "all" || track.status === statusFilter
    return matchesSearch && matchesStatus
  })

  const paginatedTracks = filteredTracks.slice((currentPage - 1) * tracksPerPage, currentPage * tracksPerPage)
  const totalPages = Math.ceil(filteredTracks.length / tracksPerPage)

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "published":
        return <Badge className="bg-green-500/20 text-green-400 border-0">Publié</Badge>
      case "draft":
        return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">Brouillon</Badge>
      case "pending":
        return <Badge className="bg-yellow-500/20 text-yellow-400 border-0">En attente</Badge>
      default:
        return <Badge>{status}</Badge>
    }
  }

  const formatStreams = (streams: number) => {
    if (streams >= 1000000) return `${(streams / 1000000).toFixed(1)}M`
    if (streams >= 1000) return `${(streams / 1000).toFixed(1)}K`
    return streams?.toString() || "0"
  }

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

  const handleAudioFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      setAudioFile(file)
    }
  }

  const handleAddTrack = async () => {
    if (!audioFile) {
      showToast("Veuillez sélectionner un fichier audio", "error")
      return
    }

    setIsUploading(true)
    try {
      const token = localStorage.getItem("auth_token")

      // Upload audio file first
      const uploadFormData = new FormData()
      uploadFormData.append("chunk", audioFile)
      uploadFormData.append("chunkIndex", "0")
      uploadFormData.append("totalChunks", "1")
      uploadFormData.append("fileName", audioFile.name)
      uploadFormData.append("fileType", audioFile.type)
      uploadFormData.append("uploadId", `track-${Date.now()}`)

      const uploadRes = await fetch("/api/upload/audio/chunk", {
        method: "POST",
        headers: token ? { Authorization: `Bearer ${token}` } : {},
        body: uploadFormData,
      })

      if (!uploadRes.ok) {
        throw new Error("Échec de l'upload du fichier audio")
      }

      const uploadData = await uploadRes.json()

      // Create track record
      const res = await fetch("/api/admin/tracks", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
        body: JSON.stringify({
          title: formData.title,
          artist_id: formData.artist_id || null,
          album_id: formData.album_id || null,
          genre_id: formData.genre_id || null,
          audio_url: uploadData.url,
          duration: 0,
          status: formData.status,
        }),
      })

      if (res.ok) {
        mutate()
        showToast("Titre ajouté avec succès")
        setShowAddTrack(false)
        resetForm()
        setAudioFile(null)
      } else {
        throw new Error("Échec de la création du titre")
      }
    } catch (error) {
      console.error("Add track error:", error)
      showToast("Erreur lors de l'ajout", "error")
    } finally {
      setIsUploading(false)
    }
  }

  const handleEditTrack = async () => {
    if (showEditTrack) {
      try {
        const res = await fetch(`/api/tracks/${showEditTrack.id}`, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            title: formData.title,
            status: formData.status,
          }),
        })
        if (res.ok) {
          mutate()
          showToast("Titre mis à jour")
          setShowEditTrack(null)
          resetForm()
        } else {
          showToast("Erreur lors de la mise à jour", "error")
        }
      } catch {
        showToast("Erreur lors de la mise à jour", "error")
      }
    }
  }

  const handleDeleteTrack = async (id: string) => {
    try {
      const res = await fetch(`/api/tracks/${id}`, { method: "DELETE" })
      if (res.ok) {
        mutate()
        showToast("Titre supprimé")
      } else {
        showToast("Erreur lors de la suppression", "error")
      }
    } catch {
      showToast("Erreur lors de la suppression", "error")
    }
    setShowDeleteConfirm(null)
  }

  const handlePublish = async (id: string) => {
    try {
      const res = await fetch(`/api/tracks/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: "published" }),
      })
      if (res.ok) {
        mutate()
        showToast("Titre publié")
      } else {
        showToast("Erreur lors de la publication", "error")
      }
    } catch {
      showToast("Erreur lors de la publication", "error")
    }
  }

  const handleReject = async (id: string) => {
    try {
      const res = await fetch(`/api/tracks/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          status: "draft",
          rejection_reason: "Le contenu ne respecte pas nos directives communautaires",
        }),
      })
      if (res.ok) {
        mutate()
        showToast("Titre rejeté")
      } else {
        showToast("Erreur lors du rejet", "error")
      }
    } catch {
      showToast("Erreur lors du rejet", "error")
    }
  }

  const handleUnpublish = async (id: string) => {
    try {
      const res = await fetch(`/api/tracks/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: "draft" }),
      })
      if (res.ok) {
        mutate()
        showToast("Titre dépublié")
      } else {
        showToast("Erreur lors de la dépublication", "error")
      }
    } catch {
      showToast("Erreur lors de la dépublication", "error")
    }
  }

  const handleDownload = async (track: Track) => {
    try {
      const response = await fetch(`/api/tracks/${track.id}/download`)
      if (response.ok) {
        const blob = await response.blob()
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement("a")
        a.href = url
        a.download = `${track.title}.mp3`
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(url)
        document.body.removeChild(a)
        showToast("Téléchargement démarré")
      } else {
        showToast("Erreur lors du téléchargement", "error")
      }
    } catch {
      showToast("Erreur lors du téléchargement", "error")
    }
  }

  const handleViewDetails = (trackId: string) => {
    router.push(`/admin/tracks/${trackId}`)
  }

  const handlePlayTrack = (track: Track) => {
    console.log("[v0] Playing track:", {
      id: track.id,
      title: track.title,
      audioUrl: track.audio_url,
    })

    if (currentTrack?.id === track.id) {
      togglePlay()
    } else {
      playTrack({
        id: track.id,
        title: track.title,
        artist: track.artist_name || "Artiste inconnu",
        image: track.cover_url || "/placeholder.svg?height=48&width=48",
        duration: Math.floor(track.duration_ms / 1000),
        audioUrl: track.audio_url,
      })
    }
  }

  const resetForm = () => {
    setFormData({
      title: "",
      artist_id: "",
      album_id: "",
      genre_id: "",
      duration: "3:30",
      status: "draft",
    })
    setAudioFile(null)
  }

  const openEditDialog = (track: Track) => {
    setFormData({
      title: track.title,
      artist_id: track.artist_id || "",
      album_id: track.album_id || "",
      genre_id: "",
      duration: formatDuration(track.duration_ms),
      status: track.status as "published" | "draft" | "pending",
    })
    setShowEditTrack(track)
  }

  const recalculateDurations = async () => {
    setIsRecalculating(true)
    try {
      const tracksToUpdate = tracks.filter(
        (track) => track.audio_url && (!track.duration_ms || track.duration_ms === 0),
      )

      if (tracksToUpdate.length === 0) {
        showToast("Aucune piste à traiter", "error")
        return
      }

      let successCount = 0
      let failCount = 0

      for (const track of tracksToUpdate) {
        try {
          const audio = new Audio(track.audio_url)

          await new Promise((resolve, reject) => {
            audio.addEventListener("loadedmetadata", resolve)
            audio.addEventListener("error", reject)
            setTimeout(() => reject(new Error("Timeout")), 10000)
          })

          const durationMs = Math.floor(audio.duration * 1000)

          await fetch(`/api/tracks/${track.id}`, {
            method: "PATCH",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ duration_ms: durationMs }),
          })

          successCount++
        } catch (error) {
          failCount++
        }
      }

      showToast(`${successCount} durées mises à jour, ${failCount} échecs`, successCount > 0 ? "success" : "error")

      mutate()
    } catch (error) {
      showToast("Échec du recalcul des durées", "error")
    } finally {
      setIsRecalculating(false)
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Loader2 className="w-8 h-8 animate-spin text-purple-500" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Titres</h1>
          <p className="text-zinc-400 text-sm">{filteredTracks.length} titres au total</p>
        </div>
        <div className="flex gap-2">
          <Button
            onClick={recalculateDurations}
            disabled={isRecalculating}
            variant="outline"
            className="border-zinc-700 hover:bg-zinc-800 bg-transparent"
          >
            {isRecalculating ? "Calcul..." : "Recalculer durées"}
          </Button>
          <Button onClick={() => setShowAddTrack(true)} className="bg-purple-600 hover:bg-purple-700">
            <Upload className="w-4 h-4 mr-2" />
            Ajouter un titre
          </Button>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col gap-4 sm:flex-row">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
          <Input
            placeholder="Rechercher par titre ou artiste..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10 bg-zinc-800/50 border-zinc-700 text-white"
          />
        </div>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-full sm:w-40 bg-zinc-800/50 border-zinc-700 text-white">
            <SelectValue placeholder="Statut" />
          </SelectTrigger>
          <SelectContent className="bg-zinc-800 border-zinc-700">
            <SelectItem value="all">Tous les statuts</SelectItem>
            <SelectItem value="published">Publié</SelectItem>
            <SelectItem value="draft">Brouillon</SelectItem>
            <SelectItem value="pending">En attente</SelectItem>
          </SelectContent>
        </Select>
        <Select value={genreFilter} onValueChange={setGenreFilter}>
          <SelectTrigger className="w-full sm:w-40 bg-zinc-800/50 border-zinc-700 text-white">
            <SelectValue placeholder="Genre" />
          </SelectTrigger>
          <SelectContent className="bg-zinc-800 border-zinc-700">
            <SelectItem value="all">Tous les genres</SelectItem>
            {genres.map((genre) => (
              <SelectItem key={genre} value={genre}>
                {genre}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Tracks Table */}
      <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-zinc-700/50">
                <th className="p-4 text-left text-sm font-medium text-zinc-400 w-12">#</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400">Titre</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden md:table-cell">Album</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden lg:table-cell">Durée</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden xl:table-cell">Streams</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400">Statut</th>
                <th className="p-4 text-right text-sm font-medium text-zinc-400">Actions</th>
              </tr>
            </thead>
            <tbody>
              {paginatedTracks.length === 0 ? (
                <tr>
                  <td colSpan={7} className="p-8 text-center text-zinc-400">
                    Aucun titre trouvé
                  </td>
                </tr>
              ) : (
                paginatedTracks.map((track, index) => (
                  <tr
                    key={track.id}
                    className="border-b border-zinc-700/30 hover:bg-zinc-700/20 transition-colors group"
                  >
                    <td className="p-4">
                      <button
                        onClick={() => handlePlayTrack(track)}
                        className="w-8 h-8 flex items-center justify-center text-zinc-400 group-hover:text-white"
                      >
                        {currentTrack?.id === track.id && isPlaying ? (
                          <Pause className="w-4 h-4 text-purple-400" />
                        ) : (
                          <>
                            <span className="group-hover:hidden">{(currentPage - 1) * tracksPerPage + index + 1}</span>
                            <Play className="w-4 h-4 hidden group-hover:block" />
                          </>
                        )}
                      </button>
                    </td>
                    <td className="p-4">
                      <div className="flex items-center gap-3">
                        <img
                          src={track.cover_url || "/placeholder.svg?height=48&width=48"}
                          alt={track.title}
                          className="w-12 h-12 rounded object-cover"
                        />
                        <div>
                          <p className="font-medium text-white">{track.title}</p>
                          <p className="text-sm text-zinc-400">{track.artist_name || "Artiste inconnu"}</p>
                        </div>
                      </div>
                    </td>
                    <td className="p-4 text-zinc-400 text-sm hidden md:table-cell">{track.album_title || "Single"}</td>
                    <td className="p-4 text-zinc-400 text-sm hidden lg:table-cell">
                      {formatDuration(track.duration_ms)}
                    </td>
                    <td className="p-4 text-zinc-400 text-sm hidden xl:table-cell">
                      {formatStreams(track.total_streams)}
                    </td>
                    <td className="p-4">{getStatusBadge(track.status)}</td>
                    <td className="p-4 text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon" className="text-zinc-400 hover:text-white">
                            <MoreVertical className="w-4 h-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="bg-zinc-800 border-zinc-700">
                          <DropdownMenuItem onClick={() => handleViewDetails(track.id)} className="text-zinc-300">
                            <Eye className="w-4 h-4 mr-2" /> Voir les détails
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => openEditDialog(track)} className="text-zinc-300">
                            <Edit className="w-4 h-4 mr-2" /> Modifier
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => handleDownload(track)} className="text-zinc-300">
                            <Download className="w-4 h-4 mr-2" /> Télécharger
                          </DropdownMenuItem>
                          {track.status === "pending" && (
                            <>
                              <DropdownMenuSeparator className="bg-zinc-700" />
                              <DropdownMenuItem onClick={() => handlePublish(track.id)} className="text-green-400">
                                <Check className="w-4 h-4 mr-2" /> Approuver
                              </DropdownMenuItem>
                              <DropdownMenuItem onClick={() => handleReject(track.id)} className="text-orange-400">
                                <X className="w-4 h-4 mr-2" /> Rejeter
                              </DropdownMenuItem>
                            </>
                          )}
                          {track.status === "draft" && (
                            <>
                              <DropdownMenuSeparator className="bg-zinc-700" />
                              <DropdownMenuItem onClick={() => handlePublish(track.id)} className="text-green-400">
                                <Check className="w-4 h-4 mr-2" /> Publier
                              </DropdownMenuItem>
                            </>
                          )}
                          {track.status === "published" && (
                            <>
                              <DropdownMenuSeparator className="bg-zinc-700" />
                              <DropdownMenuItem onClick={() => handleUnpublish(track.id)} className="text-orange-400">
                                <X className="w-4 h-4 mr-2" /> Dépublier
                              </DropdownMenuItem>
                            </>
                          )}
                          <DropdownMenuSeparator className="bg-zinc-700" />
                          <DropdownMenuItem onClick={() => setShowDeleteConfirm(track.id)} className="text-red-400">
                            <Trash2 className="w-4 h-4 mr-2" /> Supprimer
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        <div className="flex items-center justify-between p-4 border-t border-zinc-700/50">
          <p className="text-sm text-zinc-400">
            Affichage de {filteredTracks.length > 0 ? (currentPage - 1) * tracksPerPage + 1 : 0} à{" "}
            {Math.min(currentPage * tracksPerPage, filteredTracks.length)} sur {filteredTracks.length}
          </p>
          <div className="flex items-center gap-2">
            <Button
              variant="ghost"
              size="icon"
              disabled={currentPage === 1}
              onClick={() => setCurrentPage((p) => p - 1)}
              className="text-zinc-400"
            >
              <ChevronLeft className="w-4 h-4" />
            </Button>
            <span className="text-sm text-white px-3 py-1 bg-purple-600 rounded">{currentPage}</span>
            <Button
              variant="ghost"
              size="icon"
              disabled={currentPage === totalPages || totalPages === 0}
              onClick={() => setCurrentPage((p) => p + 1)}
              className="text-zinc-400"
            >
              <ChevronRight className="w-4 h-4" />
            </Button>
          </div>
        </div>
      </div>

      {/* Add Track Dialog */}
      <ConfirmDialog
        open={showAddTrack}
        onOpenChange={setShowAddTrack}
        title="Ajouter un titre"
        description="Uploader un nouveau titre sur la plateforme"
        confirmText="Ajouter"
        onConfirm={handleAddTrack}
        variant="default"
      >
        <div className="grid gap-6 py-4">
          <div className="flex items-center justify-center w-full">
            <label className="flex flex-col items-center justify-center w-full h-32 border-2 border-zinc-700 border-dashed rounded-lg cursor-pointer bg-zinc-800/50 hover:bg-zinc-800">
              <div className="flex flex-col items-center justify-center pt-5 pb-6">
                <Upload className="w-8 h-8 mb-2 text-zinc-400" />
                {audioFile ? (
                  <>
                    <p className="text-sm text-zinc-300 mb-1">{audioFile.name}</p>
                    <p className="text-xs text-zinc-500">{(audioFile.size / 1024 / 1024).toFixed(2)} MB</p>
                  </>
                ) : (
                  <>
                    <p className="text-sm text-zinc-400">Cliquez ou glissez un fichier audio</p>
                    <p className="text-xs text-zinc-500">MP3, WAV, FLAC (max. 50MB)</p>
                  </>
                )}
              </div>
              <input type="file" className="hidden" accept="audio/*" onChange={handleAudioFileChange} />
            </label>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <label htmlFor="title" className="block text-sm font-medium text-white">
                Titre
              </label>
              <Input
                id="title"
                className="bg-zinc-800 border-zinc-700"
                placeholder="Nom du titre"
                value={formData.title}
                onChange={(e) => setFormData((prev) => ({ ...prev, title: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <label htmlFor="artist" className="block text-sm font-medium text-white">
                Artiste
              </label>
              <Input
                id="artist"
                className="bg-zinc-800 border-zinc-700"
                placeholder="Nom de l'artiste"
                value={formData.artist_id}
                onChange={(e) => setFormData((prev) => ({ ...prev, artist_id: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <label htmlFor="album" className="block text-sm font-medium text-white">
                Album
              </label>
              <Input
                id="album"
                className="bg-zinc-800 border-zinc-700"
                placeholder="Nom de l'album"
                value={formData.album_id}
                onChange={(e) => setFormData((prev) => ({ ...prev, album_id: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <label htmlFor="genre" className="block text-sm font-medium text-white">
                Genre
              </label>
              <Select
                value={formData.genre_id}
                onValueChange={(v) => setFormData((prev) => ({ ...prev, genre_id: v }))}
              >
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue placeholder="Sélectionner un genre" />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  {genres.map((genre) => (
                    <SelectItem key={genre} value={genre}>
                      {genre}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="space-y-2">
            <label htmlFor="status" className="block text-sm font-medium text-white">
              Statut
            </label>
            <Select
              value={formData.status}
              onValueChange={(v) => setFormData((prev) => ({ ...prev, status: v as typeof formData.status }))}
            >
              <SelectTrigger className="bg-zinc-800 border-zinc-700">
                <SelectValue />
              </SelectTrigger>
              <SelectContent className="bg-zinc-800 border-zinc-700">
                <SelectItem value="draft">Brouillon</SelectItem>
                <SelectItem value="pending">En attente de validation</SelectItem>
                <SelectItem value="published">Publier directement</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="flex justify-end">
            <Button
              className="bg-purple-600 hover:bg-purple-700"
              onClick={handleAddTrack}
              disabled={!formData.title || !audioFile || isUploading}
            >
              {isUploading ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin mr-2" />
                  Upload...
                </>
              ) : (
                <>
                  <Plus className="w-4 h-4 mr-2" />
                  Ajouter
                </>
              )}
            </Button>
          </div>
        </div>
      </ConfirmDialog>

      {/* Edit Track Dialog */}
      <ConfirmDialog
        open={!!showEditTrack}
        onOpenChange={() => setShowEditTrack(null)}
        title="Modifier le titre"
        description="Mettre à jour les informations du titre"
        confirmText="Enregistrer"
        onConfirm={handleEditTrack}
        variant="default"
      >
        <div className="grid gap-4 py-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <label htmlFor="title-edit" className="block text-sm font-medium text-white">
                Titre
              </label>
              <Input
                id="title-edit"
                className="bg-zinc-800 border-zinc-700"
                value={formData.title}
                onChange={(e) => setFormData((prev) => ({ ...prev, title: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <label htmlFor="artist-edit" className="block text-sm font-medium text-white">
                Artiste
              </label>
              <Input
                id="artist-edit"
                className="bg-zinc-800 border-zinc-700"
                value={formData.artist_id}
                onChange={(e) => setFormData((prev) => ({ ...prev, artist_id: e.target.value }))}
                disabled
              />
            </div>
            <div className="space-y-2">
              <label htmlFor="album-edit" className="block text-sm font-medium text-white">
                Album
              </label>
              <Input
                id="album-edit"
                className="bg-zinc-800 border-zinc-700"
                value={formData.album_id}
                onChange={(e) => setFormData((prev) => ({ ...prev, album_id: e.target.value }))}
                disabled
              />
            </div>
            <div className="space-y-2">
              <label htmlFor="status-edit" className="block text-sm font-medium text-white">
                Statut
              </label>
              <Select
                value={formData.status}
                onValueChange={(v) => setFormData((prev) => ({ ...prev, status: v as typeof formData.status }))}
              >
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="draft">Brouillon</SelectItem>
                  <SelectItem value="pending">En attente</SelectItem>
                  <SelectItem value="published">Publié</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>
      </ConfirmDialog>

      {/* Delete Confirm Dialog */}
      <ConfirmDialog
        open={!!showDeleteConfirm}
        onOpenChange={() => setShowDeleteConfirm(null)}
        title="Supprimer le titre"
        description="Êtes-vous sûr de vouloir supprimer ce titre ? Cette action est irréversible."
        confirmText="Supprimer"
        onConfirm={() => showDeleteConfirm && handleDeleteTrack(showDeleteConfirm)}
        variant="destructive"
      />
    </div>
  )
}
