"use client"

import { useState } from "react"
import { useParams, useRouter } from "next/navigation"
import useSWR from "swr"
import {
  ArrowLeft,
  Edit,
  Trash2,
  Music,
  Users,
  Globe,
  Lock,
  Play,
  MoreHorizontal,
  Plus,
  Save,
  GripVertical,
  Loader2,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"

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

export default function AdminPlaylistDetailPage() {
  const params = useParams()
  const router = useRouter()
  const playlistId = params.id as string

  const { data: playlistData, error, mutate } = useSWR(`/api/playlists/${playlistId}`, fetcher)
  const playlist = playlistData?.data

  const [isEditing, setIsEditing] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [showAddTrackDialog, setShowAddTrackDialog] = useState(false)
  const [editForm, setEditForm] = useState({
    title: playlist?.title || "",
    description: playlist?.description || "",
    visibility: playlist?.is_public ? "public" : "private",
  })

  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 handleSave = async () => {
    const response = await fetch(`/api/playlists/${playlistId}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ...editForm,
        is_public: editForm.visibility === "public",
      }),
    })

    if (response.ok) {
      mutate()
      setIsEditing(false)
    }
  }

  const handleDelete = async () => {
    const response = await fetch(`/api/playlists/${playlistId}`, {
      method: "DELETE",
    })

    if (response.ok) {
      router.push("/admin/playlists")
    }
  }

  const handleRemoveTrack = async (trackId: string) => {
    const response = await fetch(`/api/playlists/${playlistId}/tracks`, {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ track_id: trackId }),
    })

    if (response.ok) {
      mutate()
    }
  }

  if (error) return <div className="text-red-400 p-4">Error loading playlist</div>
  if (!playlist)
    return (
      <div className="flex items-center justify-center p-8">
        <Loader2 className="w-8 h-8 animate-spin text-purple-500" />
      </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">{playlist.title}</h1>
          <p className="text-zinc-400">Par {playlist.creator}</p>
        </div>
        <div className="flex gap-2">
          {isEditing ? (
            <>
              <Button variant="ghost" onClick={() => setIsEditing(false)}>
                Annuler
              </Button>
              <Button onClick={handleSave} className="bg-purple-600 hover:bg-purple-700">
                <Save className="w-4 h-4 mr-2" />
                Sauvegarder
              </Button>
            </>
          ) : (
            <>
              <Button variant="outline" onClick={() => setIsEditing(true)} className="border-zinc-700">
                <Edit className="w-4 h-4 mr-2" />
                Modifier
              </Button>
              <Button variant="destructive" onClick={() => setShowDeleteDialog(true)}>
                <Trash2 className="w-4 h-4 mr-2" />
                Supprimer
              </Button>
            </>
          )}
        </div>
      </div>

      <div className="grid lg:grid-cols-3 gap-6">
        {/* Playlist Info */}
        <div className="lg:col-span-1 space-y-4">
          <Card className="bg-zinc-800/30 border-zinc-700/50">
            <CardContent className="p-4">
              <img
                src={playlist.cover || "/placeholder.svg"}
                alt={playlist.title}
                className="w-full aspect-square rounded-lg object-cover mb-4"
              />
              {isEditing ? (
                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label>Titre</Label>
                    <Input
                      value={editForm.title}
                      onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}
                      className="bg-zinc-900 border-zinc-700"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Description</Label>
                    <Textarea
                      value={editForm.description}
                      onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
                      className="bg-zinc-900 border-zinc-700 min-h-20"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Visibilite</Label>
                    <Select
                      value={editForm.visibility}
                      onValueChange={(value) => setEditForm({ ...editForm, visibility: value })}
                    >
                      <SelectTrigger className="bg-zinc-900 border-zinc-700">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent className="bg-zinc-800 border-zinc-700">
                        <SelectItem value="public">Public</SelectItem>
                        <SelectItem value="private">Prive</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              ) : (
                <div className="space-y-3">
                  <p className="text-zinc-400 text-sm">{playlist.description}</p>
                  <div className="pt-3 border-t border-zinc-700/50 space-y-2">
                    <div className="flex items-center justify-between">
                      <span className="text-zinc-400">Type</span>
                      <Badge className="bg-purple-500/20 text-purple-400 border-0">
                        {playlist.type === "editorial" ? "Editoriale" : "Utilisateur"}
                      </Badge>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-zinc-400">Visibilite</span>
                      {playlist.is_public ? (
                        <Badge className="bg-green-500/20 text-green-400 border-0">
                          <Globe className="w-3 h-3 mr-1" /> Public
                        </Badge>
                      ) : (
                        <Badge className="bg-zinc-500/20 text-zinc-400 border-0">
                          <Lock className="w-3 h-3 mr-1" /> Prive
                        </Badge>
                      )}
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-zinc-400">Creee le</span>
                      <span className="text-white">{playlist.created_at}</span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-zinc-400">Mise a jour</span>
                      <span className="text-white">{playlist.updated_at}</span>
                    </div>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Stats */}
          <Card className="bg-zinc-800/30 border-zinc-700/50">
            <CardHeader className="pb-2">
              <CardTitle className="text-white text-lg">Statistiques</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-zinc-400 flex items-center gap-2">
                  <Users className="w-4 h-4" /> Followers
                </span>
                <span className="text-white font-semibold">{formatNumber(playlist.followers)}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-zinc-400 flex items-center gap-2">
                  <Play className="w-4 h-4" /> Ecoutes totales
                </span>
                <span className="text-white font-semibold">{formatNumber(playlist.total_plays)}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-zinc-400 flex items-center gap-2">
                  <Music className="w-4 h-4" /> Titres
                </span>
                <span className="text-white">{playlist.tracks.length}</span>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Tracks */}
        <div className="lg:col-span-2">
          <Card className="bg-zinc-800/30 border-zinc-700/50">
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="text-white">Titres</CardTitle>
              <Button
                onClick={() => setShowAddTrackDialog(true)}
                size="sm"
                className="bg-purple-600 hover:bg-purple-700"
              >
                <Plus className="w-4 h-4 mr-2" />
                Ajouter
              </Button>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {playlist.tracks.map((track: any, index: number) => (
                  <div
                    key={track.id}
                    className="flex items-center gap-4 p-3 rounded-lg hover:bg-zinc-700/30 transition-colors group"
                  >
                    <GripVertical className="w-4 h-4 text-zinc-600 cursor-grab" />
                    <span className="text-zinc-500 w-6 text-center">{index + 1}</span>
                    <div className="w-10 h-10 bg-zinc-700 rounded flex items-center justify-center">
                      <Music className="w-5 h-5 text-zinc-400" />
                    </div>
                    <div className="flex-1">
                      <p className="text-white font-medium">{track.title}</p>
                      <p className="text-zinc-400 text-sm">{track.artist}</p>
                    </div>
                    <span className="text-zinc-400 text-sm">{track.duration}</span>
                    <span className="text-zinc-500 text-xs hidden sm:block">{track.added_at}</span>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="text-zinc-400 hover:text-white opacity-0 group-hover:opacity-100"
                        >
                          <MoreHorizontal className="w-4 h-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end" className="bg-zinc-800 border-zinc-700">
                        <DropdownMenuItem className="text-zinc-300">
                          <Play className="w-4 h-4 mr-2" /> Ecouter
                        </DropdownMenuItem>
                        <DropdownMenuSeparator className="bg-zinc-700" />
                        <DropdownMenuItem onClick={() => handleRemoveTrack(track.id)} className="text-red-400">
                          <Trash2 className="w-4 h-4 mr-2" /> Retirer
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Delete Dialog */}
      <Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Supprimer la playlist</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Etes-vous sur de vouloir supprimer "{playlist.title}" ? Cette action est irreversible.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowDeleteDialog(false)}>
              Annuler
            </Button>
            <Button variant="destructive" onClick={handleDelete}>
              Supprimer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Add Track Dialog */}
      <Dialog open={showAddTrackDialog} onOpenChange={setShowAddTrackDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Ajouter un titre</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Rechercher et ajouter un titre a la playlist
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <Input className="bg-zinc-800 border-zinc-700" placeholder="Rechercher un titre..." />
            <div className="space-y-2 max-h-60 overflow-y-auto">
              {["New Track 1", "New Track 2", "New Track 3"].map((track, i) => (
                <div
                  key={i}
                  className="flex items-center gap-3 p-3 rounded-lg bg-zinc-800/50 hover:bg-zinc-700/50 cursor-pointer"
                >
                  <div className="w-10 h-10 bg-zinc-700 rounded flex items-center justify-center">
                    <Music className="w-5 h-5 text-zinc-400" />
                  </div>
                  <div className="flex-1">
                    <p className="text-white">{track}</p>
                    <p className="text-zinc-400 text-sm">Artist Name</p>
                  </div>
                  <Button size="sm" variant="ghost">
                    <Plus className="w-4 h-4" />
                  </Button>
                </div>
              ))}
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowAddTrackDialog(false)}>
              Fermer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
