"use client"

import { useState, useEffect } from "react"
import { useParams, useRouter } from "next/navigation"
import {
  ArrowLeft,
  MoreHorizontal,
  Edit,
  Trash2,
  Play,
  Pause,
  Download,
  Share2,
  BarChart3,
  Clock,
  Calendar,
  Music,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useToast } from "@/hooks/use-toast"

export default function AdminTrackDetailPage() {
  const params = useParams()
  const router = useRouter()
  const { toast } = useToast()
  const [track, setTrack] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [isPlaying, setIsPlaying] = useState(false)
  const [showEditDialog, setShowEditDialog] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [editForm, setEditForm] = useState({
    title: "",
    genre: "",
    status: "",
    explicit: false,
  })

  useEffect(() => {
    const fetchTrack = async () => {
      try {
        const response = await fetch(`/api/tracks/${params.id}`)
        if (response.ok) {
          const data = await response.json()
          setTrack(data)
          setEditForm({
            title: data.title || "",
            genre: data.genre || "",
            status: data.status || "draft",
            explicit: data.explicit || false,
          })
        }
      } catch (error) {
        console.error("Error fetching track:", error)
        toast({
          title: "Erreur",
          description: "Impossible de charger le titre",
          variant: "destructive",
        })
      } finally {
        setLoading(false)
      }
    }
    fetchTrack()
  }, [params.id, toast])

  const handleSave = async () => {
    try {
      const response = await fetch(`/api/tracks/${params.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(editForm),
      })
      if (response.ok) {
        const updated = await response.json()
        setTrack({ ...track, ...editForm })
        setShowEditDialog(false)
        toast({
          title: "Succès",
          description: "Titre mis à jour",
        })
      }
    } catch (error) {
      toast({
        title: "Erreur",
        description: "Impossible de mettre à jour le titre",
        variant: "destructive",
      })
    }
  }

  const handleDelete = async () => {
    try {
      const response = await fetch(`/api/tracks/${params.id}`, {
        method: "DELETE",
      })
      if (response.ok) {
        toast({
          title: "Succès",
          description: "Titre supprimé",
        })
        router.push("/admin/tracks")
      }
    } catch (error) {
      toast({
        title: "Erreur",
        description: "Impossible de supprimer le titre",
        variant: "destructive",
      })
    }
  }

  const handleDownload = async () => {
    try {
      const response = await fetch(`/api/tracks/${params.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)
        toast({
          title: "Succès",
          description: "Téléchargement commencé",
        })
      }
    } catch (error) {
      toast({
        title: "Erreur",
        description: "Impossible de télécharger le titre",
        variant: "destructive",
      })
    }
  }

  const formatNumber = (num: number) => {
    if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`
    if (num >= 1000) return `${(num / 1000).toFixed(1)}K`
    return num.toString()
  }

  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 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>
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-white">Chargement...</div>
      </div>
    )
  }

  if (!track) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-white">Titre introuvable</div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" onClick={() => router.back()} className="text-zinc-400 hover:text-white">
          <ArrowLeft className="w-5 h-5" />
        </Button>
        <div className="flex-1">
          <h1 className="text-2xl font-bold text-white">Détail Titre</h1>
          <p className="text-zinc-400 text-sm">ID: {params.id}</p>
        </div>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" className="border-zinc-700 text-white bg-transparent">
              <MoreHorizontal className="w-4 h-4 mr-2" />
              Actions
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="bg-zinc-800 border-zinc-700">
            <DropdownMenuItem onClick={() => setShowEditDialog(true)} className="text-zinc-300">
              <Edit className="w-4 h-4 mr-2" /> Modifier
            </DropdownMenuItem>
            <DropdownMenuItem onClick={handleDownload} className="text-zinc-300">
              <Download className="w-4 h-4 mr-2" /> Télécharger
            </DropdownMenuItem>
            <DropdownMenuItem className="text-zinc-300">
              <Share2 className="w-4 h-4 mr-2" /> Partager
            </DropdownMenuItem>
            <DropdownMenuSeparator className="bg-zinc-700" />
            <DropdownMenuItem onClick={() => setShowDeleteDialog(true)} className="text-red-400">
              <Trash2 className="w-4 h-4 mr-2" /> Supprimer
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      {/* Track Info Card */}
      <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-6">
        <div className="flex flex-col md:flex-row gap-6">
          <div className="relative group">
            <img
              src={track.cover_url || "/placeholder.svg?height=200&width=200"}
              alt={track.title}
              className="w-48 h-48 rounded-lg object-cover mx-auto md:mx-0"
            />
            <button
              onClick={() => setIsPlaying(!isPlaying)}
              className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg"
            >
              {isPlaying ? (
                <Pause className="w-12 h-12 text-white" fill="white" />
              ) : (
                <Play className="w-12 h-12 text-white" fill="white" />
              )}
            </button>
          </div>
          <div className="flex-1 text-center md:text-left">
            <div className="flex flex-col md:flex-row md:items-center gap-2 mb-2">
              <h2 className="text-3xl font-bold text-white">{track.title}</h2>
              {getStatusBadge(track.status)}
              {track.explicit && <Badge className="bg-zinc-600 text-white border-0">Explicit</Badge>}
            </div>
            <p className="text-xl text-zinc-300 mb-2">{track.artist_name}</p>
            <p className="text-zinc-400 mb-4">{track.album_title || "Single"}</p>
            <div className="flex flex-wrap gap-4 justify-center md:justify-start text-sm">
              <div className="flex items-center gap-2 text-zinc-400">
                <Clock className="w-4 h-4" />
                {formatDuration(track.duration_ms || 0)}
              </div>
              <div className="flex items-center gap-2 text-zinc-400">
                <Calendar className="w-4 h-4" />
                {track.release_date || "N/A"}
              </div>
              <div className="flex items-center gap-2 text-zinc-400">
                <Music className="w-4 h-4" />
                {track.genre || "N/A"}
              </div>
              <div className="flex items-center gap-2 text-zinc-400">
                <BarChart3 className="w-4 h-4" />
                {track.total_streams || 0} écoutes
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <p className="text-zinc-400 text-sm">Streams totaux</p>
          <p className="text-2xl font-bold text-white">{formatNumber(track.total_streams || 0)}</p>
        </div>
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <p className="text-zinc-400 text-sm">Durée</p>
          <p className="text-2xl font-bold text-white">{formatDuration(track.duration_ms || 0)}</p>
        </div>
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <p className="text-zinc-400 text-sm">Genre</p>
          <p className="text-2xl font-bold text-white">{track.genre || "N/A"}</p>
        </div>
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <p className="text-zinc-400 text-sm">Statut</p>
          <p className="text-2xl font-bold text-white">{track.status}</p>
        </div>
      </div>

      {/* Tabs */}
      <Tabs defaultValue="metadata" className="space-y-4">
        <TabsList className="bg-zinc-800/50 border border-zinc-700/50">
          <TabsTrigger value="metadata" className="data-[state=active]:bg-purple-600">
            Métadonnées
          </TabsTrigger>
          <TabsTrigger value="audio" className="data-[state=active]:bg-purple-600">
            Audio
          </TabsTrigger>
        </TabsList>

        <TabsContent value="metadata" className="space-y-4">
          <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
            <h3 className="font-semibold text-white mb-4">Informations techniques</h3>
            <div className="grid md:grid-cols-2 gap-4">
              <div className="space-y-3">
                <div className="flex justify-between">
                  <span className="text-zinc-400">Titre</span>
                  <span className="text-white">{track.title}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-zinc-400">Artiste</span>
                  <span className="text-white">{track.artist_name}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-zinc-400">Genre</span>
                  <span className="text-white">{track.genre || "N/A"}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-zinc-400">Durée</span>
                  <span className="text-white">{formatDuration(track.duration_ms || 0)}</span>
                </div>
              </div>
              <div className="space-y-3">
                <div className="flex justify-between">
                  <span className="text-zinc-400">Date de sortie</span>
                  <span className="text-white">{track.release_date || "N/A"}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-zinc-400">Explicit</span>
                  <span className="text-white">{track.explicit ? "Oui" : "Non"}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-zinc-400">Statut</span>
                  <span className="text-white">{track.status}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-zinc-400">Streams</span>
                  <span className="text-white">{track.total_streams || 0}</span>
                </div>
              </div>
            </div>
          </div>
        </TabsContent>

        <TabsContent value="audio" className="space-y-4">
          <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
            <h3 className="font-semibold text-white mb-4">Fichier audio</h3>
            <div className="space-y-3">
              <div className="flex justify-between">
                <span className="text-zinc-400">URL</span>
                <span className="text-white text-sm truncate max-w-md">{track.audio_url}</span>
              </div>
              {track.audio_url && (
                <audio controls className="w-full mt-4">
                  <source src={track.audio_url} type="audio/mpeg" />
                  Votre navigateur ne supporte pas l'élément audio.
                </audio>
              )}
            </div>
          </div>
        </TabsContent>
      </Tabs>

      {/* Edit Dialog */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white max-w-lg">
          <DialogHeader>
            <DialogTitle>Modifier le titre</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Titre</Label>
              <Input
                value={editForm.title}
                onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
              />
            </div>
            <div className="space-y-2">
              <Label>Genre</Label>
              <Input
                value={editForm.genre}
                onChange={(e) => setEditForm({ ...editForm, genre: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
              />
            </div>
            <div className="space-y-2">
              <Label>Statut</Label>
              <Select value={editForm.status} onValueChange={(value) => setEditForm({ ...editForm, status: value })}>
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="published">Publié</SelectItem>
                  <SelectItem value="draft">Brouillon</SelectItem>
                  <SelectItem value="pending">En attente</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Explicit</Label>
              <Select
                value={editForm.explicit ? "yes" : "no"}
                onValueChange={(value) => setEditForm({ ...editForm, explicit: value === "yes" })}
              >
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="no">Non</SelectItem>
                  <SelectItem value="yes">Oui</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowEditDialog(false)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleSave}>
              Sauvegarder
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Dialog */}
      <Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Supprimer le titre</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Êtes-vous sûr de vouloir supprimer "{track.title}" ? Cette action est irréversible.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowDeleteDialog(false)}>
              Annuler
            </Button>
            <Button variant="destructive" onClick={handleDelete}>
              Supprimer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
