"use client"

import { useState } from "react"
import { Search, Plus, MoreHorizontal, Edit, Trash2, Music, TrendingUp, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { useToast } from "@/hooks/use-toast"
import useSWR from "swr"

interface Genre {
  id: string
  name: string
  slug: string
  description: string | null
  color: string | null
  icon_url: string | null
  is_featured: boolean
  track_count: number
}

const fetcher = (url: string) => {
  const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null
  console.log("[v0] Fetcher called for URL:", url)
  return fetch(url, {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  })
    .then((res) => {
      console.log("[v0] Fetcher response status:", res.status)
      return res.json()
    })
    .then((data) => {
      console.log("[v0] Fetcher parsed data:", data)
      console.log("[v0] Number of genres in response:", data?.data?.length || 0)
      return data
    })
}

export default function AdminGenresPage() {
  const { toast } = useToast()
  const { data, error, isLoading, mutate } = useSWR<{ data: Genre[] }>("/api/genres", fetcher)

  const genres = data?.data || []
  console.log("[v0] Current genres state:", {
    genresCount: genres.length,
    isLoading,
    hasError: !!error,
    dataExists: !!data,
  })

  const [searchQuery, setSearchQuery] = useState("")
  const [showAddDialog, setShowAddDialog] = useState(false)
  const [editingGenre, setEditingGenre] = useState<Genre | null>(null)
  const [formData, setFormData] = useState({
    name: "",
    slug: "",
    description: "",
    color: "#FF6B9D",
    is_featured: false,
  })
  const [isSaving, setIsSaving] = useState(false)

  const filteredGenres = genres.filter((genre) => genre.name.toLowerCase().includes(searchQuery.toLowerCase()))

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

  const getAuthHeaders = () => {
    const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null
    return {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    }
  }

  const openAddDialog = () => {
    setFormData({ name: "", slug: "", description: "", color: "#FF6B9D", is_featured: false })
    setShowAddDialog(true)
  }

  const openEditDialog = (genre: Genre) => {
    setFormData({
      name: genre.name,
      slug: genre.slug,
      description: genre.description || "",
      color: genre.color || "#FF6B9D",
      is_featured: genre.is_featured,
    })
    setEditingGenre(genre)
  }

  const handleSave = async () => {
    setIsSaving(true)
    try {
      const url = editingGenre ? `/api/genres/${editingGenre.id}` : "/api/genres"
      const method = editingGenre ? "PUT" : "POST"

      console.log("[v0] Creating genre with data:", formData)
      console.log("[v0] Request URL:", url, "Method:", method)

      const res = await fetch(url, {
        method,
        headers: getAuthHeaders(),
        body: JSON.stringify(formData),
      })

      console.log("[v0] Create genre response status:", res.status)
      const responseData = await res.json()
      console.log("[v0] Create genre response data:", responseData)

      if (res.ok) {
        console.log("[v0] Before mutate - current genres count:", genres.length)
        console.log("[v0] Triggering mutate to refresh genres list")

        const newData = await mutate()

        console.log("[v0] After mutate - newData:", newData)
        console.log("[v0] After mutate - genres count:", newData?.data?.length || 0)

        toast({
          title: editingGenre ? "Genre modifié" : "Genre créé",
          description: `Le genre "${formData.name}" a été ${editingGenre ? "modifié" : "créé"} avec succès.`,
        })

        setShowAddDialog(false)
        setEditingGenre(null)
      } else {
        throw new Error("Failed to save")
      }
    } catch (error) {
      console.error("[v0] Error creating genre:", error)
      toast({
        title: "Erreur",
        description: "Une erreur est survenue lors de la sauvegarde.",
        variant: "destructive",
      })
    } finally {
      setIsSaving(false)
    }
  }

  const toggleFeatured = async (genre: Genre) => {
    try {
      const res = await fetch(`/api/genres/${genre.id}`, {
        method: "PUT",
        headers: getAuthHeaders(),
        body: JSON.stringify({ is_featured: !genre.is_featured }),
      })

      if (res.ok) {
        toast({
          title: genre.is_featured ? "Retiré de la une" : "Mis en avant",
          description: `Le genre "${genre.name}" a été ${genre.is_featured ? "retiré de la une" : "mis en avant"}.`,
        })
        await mutate()
      }
    } catch (error) {
      toast({ title: "Erreur", description: "Une erreur est survenue.", variant: "destructive" })
    }
  }

  const deleteGenre = async (genre: Genre) => {
    if (!confirm(`Supprimer le genre "${genre.name}" ?`)) return

    try {
      const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null
      const res = await fetch(`/api/genres/${genre.id}`, {
        method: "DELETE",
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      })

      if (res.ok) {
        toast({ title: "Genre supprimé", description: `Le genre "${genre.name}" a été supprimé.` })
        await mutate()
      }
    } catch (error) {
      toast({ title: "Erreur", description: "Une erreur est survenue.", variant: "destructive" })
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <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">Genres</h1>
          <p className="text-zinc-400 text-sm">{genres.length} genres au total</p>
        </div>
        <Button onClick={openAddDialog} className="bg-purple-600 hover:bg-purple-700">
          <Plus className="w-4 h-4 mr-2" />
          Ajouter un genre
        </Button>
      </div>

      {/* Search */}
      <div className="relative max-w-md">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
        <Input
          placeholder="Rechercher un genre..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          className="pl-10 bg-zinc-800/50 border-zinc-700 text-white"
        />
      </div>

      {/* Genres Grid */}
      {filteredGenres.length === 0 ? (
        <div className="text-center py-12 bg-zinc-800/30 rounded-xl border border-zinc-700/50">
          <Music className="w-12 h-12 mx-auto mb-4 text-zinc-600" />
          <p className="text-zinc-400">Aucun genre trouvé</p>
          <Button onClick={openAddDialog} className="mt-4 bg-purple-600 hover:bg-purple-700">
            <Plus className="w-4 h-4 mr-2" />
            Ajouter un genre
          </Button>
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {filteredGenres.map((genre) => (
            <div
              key={genre.id}
              className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4 hover:bg-zinc-800/50 transition-colors"
            >
              <div className="flex items-start justify-between mb-4">
                <div
                  className="w-12 h-12 rounded-lg flex items-center justify-center text-2xl"
                  style={{ backgroundColor: `${genre.color || "#888"}20` }}
                >
                  <Music className="w-6 h-6" style={{ color: genre.color || "#888" }} />
                </div>
                <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={() => openEditDialog(genre)} className="text-zinc-300">
                      <Edit className="w-4 h-4 mr-2" /> Modifier
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => toggleFeatured(genre)} className="text-zinc-300">
                      <TrendingUp className="w-4 h-4 mr-2" />
                      {genre.is_featured ? "Retirer de la une" : "Mettre en avant"}
                    </DropdownMenuItem>
                    <DropdownMenuSeparator className="bg-zinc-700" />
                    <DropdownMenuItem onClick={() => deleteGenre(genre)} className="text-red-400">
                      <Trash2 className="w-4 h-4 mr-2" /> Supprimer
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
              <div>
                <div className="flex items-center gap-2 mb-1">
                  <h3 className="font-semibold text-white">{genre.name}</h3>
                  {genre.is_featured && (
                    <span className="px-2 py-0.5 text-xs rounded-full bg-purple-500/20 text-purple-400">Featured</span>
                  )}
                </div>
                <p className="text-zinc-400 text-sm mb-2">/{genre.slug}</p>
                <div className="flex items-center gap-2 text-zinc-400 text-sm">
                  <Music className="w-4 h-4" />
                  {formatNumber(genre.track_count || 0)} titres
                </div>
              </div>
              <div className="mt-3 pt-3 border-t border-zinc-700/50">
                <div className="flex items-center gap-2">
                  <div className="w-4 h-4 rounded" style={{ backgroundColor: genre.color || "#888" }} />
                  <span className="text-zinc-400 text-sm font-mono">{genre.color || "N/A"}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Add/Edit Dialog */}
      <Dialog
        open={showAddDialog || !!editingGenre}
        onOpenChange={(open) => {
          if (!open) {
            setShowAddDialog(false)
            setEditingGenre(null)
          }
        }}
      >
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>{editingGenre ? "Modifier le genre" : "Ajouter un genre"}</DialogTitle>
            <DialogDescription className="text-zinc-400">
              {editingGenre ? "Modifiez les informations du genre" : "Créer un nouveau genre musical"}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Nom</Label>
                <Input
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  className="bg-zinc-800 border-zinc-700"
                  placeholder="Pop"
                />
              </div>
              <div className="space-y-2">
                <Label>Slug</Label>
                <Input
                  value={formData.slug}
                  onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
                  className="bg-zinc-800 border-zinc-700"
                  placeholder="pop"
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Couleur</Label>
                <div className="flex gap-2">
                  <Input
                    type="color"
                    value={formData.color}
                    onChange={(e) => setFormData({ ...formData, color: e.target.value })}
                    className="w-12 h-10 p-1 bg-zinc-800 border-zinc-700"
                  />
                  <Input
                    value={formData.color}
                    onChange={(e) => setFormData({ ...formData, color: e.target.value })}
                    className="bg-zinc-800 border-zinc-700 font-mono"
                    placeholder="#FF6B9D"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label>En avant</Label>
                <div className="flex items-center h-10">
                  <input
                    type="checkbox"
                    checked={formData.is_featured}
                    onChange={(e) => setFormData({ ...formData, is_featured: e.target.checked })}
                    className="w-5 h-5 rounded bg-zinc-800 border-zinc-700"
                  />
                  <span className="ml-2 text-zinc-400 text-sm">Mettre en avant</span>
                </div>
              </div>
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Textarea
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                className="bg-zinc-800 border-zinc-700 min-h-20"
                placeholder="Description du genre..."
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="ghost"
              onClick={() => {
                setShowAddDialog(false)
                setEditingGenre(null)
              }}
              disabled={isSaving}
            >
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleSave} disabled={isSaving}>
              {isSaving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
              {editingGenre ? "Sauvegarder" : "Créer"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
