"use client"

import { useState } from "react"
import useSWR from "swr"
import { Search, Plus, MoreHorizontal, Edit, Trash2, Eye, XCircle, Loader2, CheckCircle } 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 { 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 { Textarea } from "@/components/ui/textarea"
import { ConfirmDialog } from "@/components/confirm-dialog"
import { useToast } from "@/hooks/use-toast"
import { VerifiedBadge } from "@/components/verified-badge"

interface Artist {
  id: string
  user_id: string | null
  name: string
  bio: string | null
  avatar_url: string | null
  cover_url: string | null
  country: string | null
  genres: string[] | null
  is_verified: boolean
  monthly_listeners: number
  total_followers: number
  created_at: string
  track_count: number
  album_count: number
  total_streams: number
}

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

export default function AdminArtistsPage() {
  const { data, error, isLoading, mutate } = useSWR<{ data: Artist[]; total: number }>(
    "/api/artists?limit=100",
    fetcher,
  )
  const { toast } = useToast()

  const [searchQuery, setSearchQuery] = useState("")
  const [verifiedFilter, setVerifiedFilter] = useState("all")
  const [showAddArtist, setShowAddArtist] = useState(false)
  const [showEditArtist, setShowEditArtist] = useState<Artist | null>(null)
  const [showArtistDetail, setShowArtistDetail] = useState<Artist | null>(null)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(null)
  const [isSubmitting, setIsSubmitting] = useState(false)

  // Form state
  const [formData, setFormData] = useState({
    name: "",
    genre: "",
    bio: "",
    country: "",
  })

  const artists = data?.data || []

  const filteredArtists = artists.filter((artist) => {
    const matchesSearch = artist.name.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesVerified =
      verifiedFilter === "all" ||
      (verifiedFilter === "verified" && artist.is_verified) ||
      (verifiedFilter === "unverified" && !artist.is_verified)
    return matchesSearch && matchesVerified
  })

  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 handleAddArtist = async () => {
    setIsSubmitting(true)
    try {
      const response = await fetch("/api/artists", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: formData.name,
          bio: formData.bio,
          country: formData.country,
          genres: formData.genre ? [formData.genre] : [],
        }),
      })

      if (!response.ok) throw new Error("Failed to create artist")

      toast({ title: "Artiste créé", description: "L'artiste a été ajouté avec succès" })
      mutate()
      setShowAddArtist(false)
      resetForm()
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible de créer l'artiste", variant: "destructive" })
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleEditArtist = async () => {
    if (!showEditArtist) return
    setIsSubmitting(true)
    try {
      const response = await fetch(`/api/artists/${showEditArtist.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: formData.name,
          bio: formData.bio,
          country: formData.country,
          genres: formData.genre ? [formData.genre] : [],
        }),
      })

      if (!response.ok) throw new Error("Failed to update artist")

      toast({ title: "Artiste modifié", description: "Les informations ont été mises à jour" })
      mutate()
      setShowEditArtist(null)
      resetForm()
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible de modifier l'artiste", variant: "destructive" })
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleDeleteArtist = async (id: string) => {
    try {
      const response = await fetch(`/api/artists/${id}`, { method: "DELETE" })
      if (!response.ok) throw new Error("Failed to delete artist")

      toast({ title: "Artiste supprimé", description: "L'artiste a été supprimé avec succès" })
      mutate()
      setShowDeleteConfirm(null)
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible de supprimer l'artiste", variant: "destructive" })
    }
  }

  const handleToggleVerification = async (artist: Artist) => {
    try {
      const response = await fetch(`/api/artists/${artist.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ is_verified: !artist.is_verified }),
      })

      if (!response.ok) throw new Error("Failed to update verification")

      toast({
        title: artist.is_verified ? "Vérification retirée" : "Artiste vérifié",
        description: artist.is_verified ? "Le badge a été retiré" : "Le badge a été ajouté",
      })
      mutate()
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible de modifier la vérification", variant: "destructive" })
    }
  }

  const resetForm = () => {
    setFormData({ name: "", genre: "", bio: "", country: "" })
  }

  const openEditDialog = (artist: Artist) => {
    setFormData({
      name: artist.name,
      genre: artist.genres?.[0] || "",
      bio: artist.bio || "",
      country: artist.country || "",
    })
    setShowEditArtist(artist)
  }

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

  if (error) {
    return (
      <div className="flex items-center justify-center h-96 text-red-400">Erreur lors du chargement des artistes</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">Artistes</h1>
          <p className="text-zinc-400 text-sm">{filteredArtists.length} artistes au total</p>
        </div>
        <Button onClick={() => setShowAddArtist(true)} className="bg-purple-600 hover:bg-purple-700">
          <Plus className="w-4 h-4 mr-2" />
          Ajouter un artiste
        </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 un artiste..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10 bg-zinc-800/50 border-zinc-700 text-white"
          />
        </div>
        <Select value={verifiedFilter} onValueChange={setVerifiedFilter}>
          <SelectTrigger className="w-full sm:w-40 bg-zinc-800/50 border-zinc-700 text-white">
            <SelectValue placeholder="Vérification" />
          </SelectTrigger>
          <SelectContent className="bg-zinc-800 border-zinc-700">
            <SelectItem value="all">Tous</SelectItem>
            <SelectItem value="verified">Vérifié</SelectItem>
            <SelectItem value="unverified">Non vérifié</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Artists Grid */}
      {filteredArtists.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16 text-zinc-400">
          <p className="text-lg">Aucun artiste trouvé</p>
          <p className="text-sm">Ajoutez des artistes pour les voir ici</p>
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {filteredArtists.map((artist) => (
            <div
              key={artist.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">
                <div className="flex items-center gap-4">
                  <img
                    src={artist.avatar_url || "/placeholder.svg?height=64&width=64&query=artist"}
                    alt={artist.name}
                    className="w-16 h-16 rounded-full object-cover"
                  />
                  <div>
                    <div className="flex items-center gap-2">
                      <h3 className="font-semibold text-white">{artist.name}</h3>
                      {artist.is_verified && <VerifiedBadge size="sm" />}
                    </div>
                    <p className="text-sm text-zinc-400">{artist.genres?.[0] || "Non défini"}</p>
                    <p className="text-sm text-purple-400">
                      {formatNumber(artist.monthly_listeners || 0)} auditeurs/mois
                    </p>
                  </div>
                </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={() => setShowArtistDetail(artist)} className="text-zinc-300">
                      <Eye className="w-4 h-4 mr-2" /> Voir le profil
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => openEditDialog(artist)} className="text-zinc-300">
                      <Edit className="w-4 h-4 mr-2" /> Modifier
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => handleToggleVerification(artist)} className="text-zinc-300">
                      {artist.is_verified ? (
                        <>
                          <XCircle className="w-4 h-4 mr-2" /> Retirer vérification
                        </>
                      ) : (
                        <>
                          <CheckCircle className="w-4 h-4 mr-2" /> Vérifier
                        </>
                      )}
                    </DropdownMenuItem>
                    <DropdownMenuSeparator className="bg-zinc-700" />
                    <DropdownMenuItem onClick={() => setShowDeleteConfirm(artist.id)} className="text-red-400">
                      <Trash2 className="w-4 h-4 mr-2" /> Supprimer
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
              <div className="grid grid-cols-3 gap-2 mt-4 pt-4 border-t border-zinc-700/50">
                <div className="text-center">
                  <p className="text-lg font-semibold text-white">{formatNumber(artist.total_followers || 0)}</p>
                  <p className="text-xs text-zinc-400">Followers</p>
                </div>
                <div className="text-center">
                  <p className="text-lg font-semibold text-white">{artist.track_count || 0}</p>
                  <p className="text-xs text-zinc-400">Titres</p>
                </div>
                <div className="text-center">
                  <p className="text-lg font-semibold text-white">{artist.album_count || 0}</p>
                  <p className="text-xs text-zinc-400">Albums</p>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Add Artist Dialog */}
      <Dialog open={showAddArtist} onOpenChange={setShowAddArtist}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Ajouter un artiste</DialogTitle>
            <DialogDescription className="text-zinc-400">Créer un nouveau profil artiste</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Nom de l'artiste</Label>
              <Input
                className="bg-zinc-800 border-zinc-700"
                placeholder="Nom"
                value={formData.name}
                onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Genre musical</Label>
              <Input
                className="bg-zinc-800 border-zinc-700"
                placeholder="Pop, Rock, Jazz..."
                value={formData.genre}
                onChange={(e) => setFormData((prev) => ({ ...prev, genre: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Pays</Label>
              <Input
                className="bg-zinc-800 border-zinc-700"
                placeholder="France, Côte d'Ivoire..."
                value={formData.country}
                onChange={(e) => setFormData((prev) => ({ ...prev, country: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Biographie</Label>
              <Textarea
                className="bg-zinc-800 border-zinc-700 min-h-24"
                placeholder="Description de l'artiste..."
                value={formData.bio}
                onChange={(e) => setFormData((prev) => ({ ...prev, bio: e.target.value }))}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowAddArtist(false)}>
              Annuler
            </Button>
            <Button
              className="bg-purple-600 hover:bg-purple-700"
              onClick={handleAddArtist}
              disabled={!formData.name || isSubmitting}
            >
              {isSubmitting ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
              Créer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit Artist Dialog */}
      <Dialog open={!!showEditArtist} onOpenChange={() => setShowEditArtist(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Modifier l'artiste</DialogTitle>
            <DialogDescription className="text-zinc-400">Mettre à jour les informations</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Nom de l'artiste</Label>
              <Input
                className="bg-zinc-800 border-zinc-700"
                value={formData.name}
                onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Genre musical</Label>
              <Input
                className="bg-zinc-800 border-zinc-700"
                value={formData.genre}
                onChange={(e) => setFormData((prev) => ({ ...prev, genre: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Pays</Label>
              <Input
                className="bg-zinc-800 border-zinc-700"
                value={formData.country}
                onChange={(e) => setFormData((prev) => ({ ...prev, country: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Biographie</Label>
              <Textarea
                className="bg-zinc-800 border-zinc-700 min-h-24"
                value={formData.bio}
                onChange={(e) => setFormData((prev) => ({ ...prev, bio: e.target.value }))}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowEditArtist(null)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleEditArtist} disabled={isSubmitting}>
              {isSubmitting ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
              Enregistrer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Artist Detail Dialog */}
      <Dialog open={!!showArtistDetail} onOpenChange={() => setShowArtistDetail(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white max-w-lg">
          <DialogHeader>
            <DialogTitle>Profil artiste</DialogTitle>
          </DialogHeader>
          {showArtistDetail && (
            <div className="space-y-6 py-4">
              <div className="flex items-center gap-4">
                <img
                  src={showArtistDetail.avatar_url || "/placeholder.svg?height=96&width=96&query=artist"}
                  alt={showArtistDetail.name}
                  className="w-24 h-24 rounded-full object-cover"
                />
                <div>
                  <div className="flex items-center gap-2">
                    <h3 className="text-2xl font-bold">{showArtistDetail.name}</h3>
                    {showArtistDetail.is_verified && <VerifiedBadge size="md" />}
                  </div>
                  <p className="text-zinc-400">{showArtistDetail.genres?.[0] || "Genre non défini"}</p>
                  {showArtistDetail.country && <p className="text-zinc-500 text-sm">{showArtistDetail.country}</p>}
                </div>
              </div>
              {showArtistDetail.bio && (
                <div className="bg-zinc-800/50 rounded-lg p-4">
                  <p className="text-zinc-400 text-sm mb-1">Biographie</p>
                  <p className="text-white text-sm">{showArtistDetail.bio}</p>
                </div>
              )}
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-zinc-800/50 rounded-lg p-4">
                  <p className="text-zinc-400 text-sm">Auditeurs mensuels</p>
                  <p className="text-xl font-bold text-white">
                    {formatNumber(showArtistDetail.monthly_listeners || 0)}
                  </p>
                </div>
                <div className="bg-zinc-800/50 rounded-lg p-4">
                  <p className="text-zinc-400 text-sm">Followers</p>
                  <p className="text-xl font-bold text-white">{formatNumber(showArtistDetail.total_followers || 0)}</p>
                </div>
              </div>
              <div className="text-xs text-zinc-500">
                Inscrit le {new Date(showArtistDetail.created_at).toLocaleDateString("fr-FR")}
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <ConfirmDialog
        open={showDeleteConfirm !== null}
        onOpenChange={() => setShowDeleteConfirm(null)}
        title="Supprimer l'artiste"
        description="Êtes-vous sûr de vouloir supprimer cet artiste ? Tous ses titres et albums seront également supprimés."
        confirmText="Supprimer"
        variant="destructive"
        onConfirm={() => showDeleteConfirm && handleDeleteArtist(showDeleteConfirm)}
      />
    </div>
  )
}
