"use client"

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

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

export default function AdminPlaylistsPage() {
  const router = useRouter()
  const { data, isLoading, error } = useSWR("/api/admin/playlists", fetcher)

  const [searchQuery, setSearchQuery] = useState("")
  const [typeFilter, setTypeFilter] = useState("all")
  const [showAddPlaylist, setShowAddPlaylist] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [showEditDialog, setShowEditDialog] = useState(false)
  const [selectedPlaylist, setSelectedPlaylist] = useState<any | null>(null)
  const [newPlaylist, setNewPlaylist] = useState({ title: "", description: "", visibility: "public" })

  const playlists = data?.playlists || []

  const filteredPlaylists = playlists.filter((playlist: any) => {
    const matchesSearch =
      playlist.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      playlist.creator.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesType = typeFilter === "all" || playlist.type === typeFilter
    return matchesSearch && matchesType
  })

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

  const handleView = (playlist: any) => {
    router.push(`/admin/playlists/${playlist.id}`)
  }

  const handleEdit = (playlist: any) => {
    setSelectedPlaylist(playlist)
    setShowEditDialog(true)
  }

  const handleDelete = (playlist: any) => {
    setSelectedPlaylist(playlist)
    setShowDeleteDialog(true)
  }

  const confirmDelete = async () => {
    if (selectedPlaylist) {
      await fetch(`/api/playlists/${selectedPlaylist.id}`, { method: "DELETE" })
      mutate("/api/admin/playlists")
    }
    setShowDeleteDialog(false)
    setSelectedPlaylist(null)
  }

  const handleSaveEdit = async () => {
    if (selectedPlaylist) {
      await fetch(`/api/playlists/${selectedPlaylist.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(selectedPlaylist),
      })
      mutate("/api/admin/playlists")
    }
    setShowEditDialog(false)
    setSelectedPlaylist(null)
  }

  const handleCreatePlaylist = async () => {
    await fetch("/api/admin/playlists", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(newPlaylist),
    })
    mutate("/api/admin/playlists")
    setShowAddPlaylist(false)
    setNewPlaylist({ title: "", description: "", visibility: "public" })
  }

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

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <p className="text-red-400">Erreur lors du chargement des données</p>
      </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">Playlists</h1>
          <p className="text-zinc-400 text-sm">{filteredPlaylists.length} playlists au total</p>
        </div>
        <Button onClick={() => setShowAddPlaylist(true)} className="bg-purple-600 hover:bg-purple-700">
          <Plus className="w-4 h-4 mr-2" />
          Créer une playlist
        </Button>
      </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 une playlist..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10 bg-zinc-800/50 border-zinc-700 text-white"
          />
        </div>
        <Select value={typeFilter} onValueChange={setTypeFilter}>
          <SelectTrigger className="w-full sm:w-40 bg-zinc-800/50 border-zinc-700 text-white">
            <SelectValue placeholder="Type" />
          </SelectTrigger>
          <SelectContent className="bg-zinc-800 border-zinc-700">
            <SelectItem value="all">Tous les types</SelectItem>
            <SelectItem value="editorial">Éditoriale</SelectItem>
            <SelectItem value="user">Utilisateur</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Playlists 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">Playlist</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden md:table-cell">Créateur</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden lg:table-cell">Titres</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden lg:table-cell">Followers</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400">Visibilité</th>
                <th className="p-4 text-right text-sm font-medium text-zinc-400">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filteredPlaylists.length > 0 ? (
                filteredPlaylists.map((playlist: any) => (
                  <tr key={playlist.id} className="border-b border-zinc-700/30 hover:bg-zinc-700/20 transition-colors">
                    <td className="p-4">
                      <div className="flex items-center gap-3">
                        <img
                          src={playlist.cover || "/placeholder.svg"}
                          alt={playlist.title}
                          className="w-12 h-12 rounded object-cover"
                        />
                        <div>
                          <p className="font-medium text-white">{playlist.title}</p>
                          <Badge
                            className={
                              playlist.type === "editorial"
                                ? "bg-purple-500/20 text-purple-400 border-0"
                                : "bg-zinc-500/20 text-zinc-400 border-0"
                            }
                          >
                            {playlist.type === "editorial" ? "Éditoriale" : "Utilisateur"}
                          </Badge>
                        </div>
                      </div>
                    </td>
                    <td className="p-4 text-zinc-400 hidden md:table-cell">{playlist.creator}</td>
                    <td className="p-4 text-zinc-400 hidden lg:table-cell">
                      <span className="flex items-center gap-1">
                        <Music className="w-4 h-4" /> {playlist.tracks}
                      </span>
                    </td>
                    <td className="p-4 text-zinc-400 hidden lg:table-cell">
                      <span className="flex items-center gap-1">
                        <Users className="w-4 h-4" /> {formatFollowers(playlist.followers)}
                      </span>
                    </td>
                    <td className="p-4">
                      {playlist.visibility === "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" /> Privé
                        </Badge>
                      )}
                    </td>
                    <td className="p-4 text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon" className="text-zinc-400 hover:text-white">
                            <MoreHorizontal className="w-4 h-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="bg-zinc-800 border-zinc-700">
                          <DropdownMenuItem onClick={() => handleView(playlist)} className="text-zinc-300">
                            <Eye className="w-4 h-4 mr-2" /> Voir
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => handleEdit(playlist)} className="text-zinc-300">
                            <Edit className="w-4 h-4 mr-2" /> Modifier
                          </DropdownMenuItem>
                          <DropdownMenuSeparator className="bg-zinc-700" />
                          <DropdownMenuItem onClick={() => handleDelete(playlist)} className="text-red-400">
                            <Trash2 className="w-4 h-4 mr-2" /> Supprimer
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={6} className="p-8 text-center text-zinc-400">
                    Aucune playlist trouvée
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add Playlist Dialog */}
      <Dialog open={showAddPlaylist} onOpenChange={setShowAddPlaylist}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Créer une playlist</DialogTitle>
            <DialogDescription className="text-zinc-400">Créer une nouvelle playlist éditoriale</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Nom de la playlist</Label>
              <Input
                value={newPlaylist.title}
                onChange={(e) => setNewPlaylist({ ...newPlaylist, title: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
                placeholder="Ma playlist"
              />
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Textarea
                value={newPlaylist.description}
                onChange={(e) => setNewPlaylist({ ...newPlaylist, description: e.target.value })}
                className="bg-zinc-800 border-zinc-700 min-h-20"
                placeholder="Description..."
              />
            </div>
            <div className="space-y-2">
              <Label>Visibilité</Label>
              <Select
                value={newPlaylist.visibility}
                onValueChange={(value) => setNewPlaylist({ ...newPlaylist, visibility: value })}
              >
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="public">Public</SelectItem>
                  <SelectItem value="private">Privé</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowAddPlaylist(false)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleCreatePlaylist}>
              Créer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit Playlist Dialog */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Modifier la playlist</DialogTitle>
            <DialogDescription className="text-zinc-400">Modifiez les détails de la playlist</DialogDescription>
          </DialogHeader>
          {selectedPlaylist && (
            <div className="space-y-4 py-4">
              <div className="space-y-2">
                <Label>Nom de la playlist</Label>
                <Input
                  value={selectedPlaylist.title}
                  onChange={(e) => setSelectedPlaylist({ ...selectedPlaylist, title: e.target.value })}
                  className="bg-zinc-800 border-zinc-700"
                />
              </div>
              <div className="space-y-2">
                <Label>Visibilité</Label>
                <Select
                  value={selectedPlaylist.visibility}
                  onValueChange={(value) => setSelectedPlaylist({ ...selectedPlaylist, visibility: value })}
                >
                  <SelectTrigger className="bg-zinc-800 border-zinc-700">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-zinc-800 border-zinc-700">
                    <SelectItem value="public">Public</SelectItem>
                    <SelectItem value="private">Privé</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowEditDialog(false)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleSaveEdit}>
              Sauvegarder
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation 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">
              Êtes-vous sûr de vouloir supprimer "{selectedPlaylist?.title}" ? Cette action est irréversible.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowDeleteDialog(false)}>
              Annuler
            </Button>
            <Button variant="destructive" onClick={confirmDelete}>
              Supprimer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
