"use client"

import { useState } from "react"
import { useParams, useRouter } from "next/navigation"
import useSWR from "swr"
import {
  ArrowLeft,
  MoreHorizontal,
  Edit,
  Trash2,
  CheckCircle,
  XCircle,
  Music,
  Disc3,
  Users,
  TrendingUp,
  Play,
  DollarSign,
  Calendar,
  Globe,
  Mail,
  Loader2,
} 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 { Textarea } from "@/components/ui/textarea"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

interface Artist {
  id: string
  name: string
  genre: string
  bio: string
  email: string
  website: string
  image: string
  coverImage: string
  city: string
  country: string
  verified: boolean
  monthlyListeners: number
  totalStreams: number
  tracksCount: number
  albumsCount: number
  joinedDate: string
  socialLinks: {
    instagram: string
    twitter: string
    youtube: string
  }
  topTracks: Array<{
    title: string
    album: string
    streams: number
  }>
  albums: Array<{
    title: string
    year: string
    tracks: number
    streams: number
  }>
  earnings: {
    total: number
    thisMonth: number
    lastMonth: number
    pending: number
  }
}

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

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

  const { data: artistData, error, mutate } = useSWR(`/api/artists/${artistId}`, fetcher)
  const artist = artistData?.data

  const [showEditDialog, setShowEditDialog] = useState(false)
  const [showVerifyDialog, setShowVerifyDialog] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)

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

  const formatCurrency = (num: number) => {
    return new Intl.NumberFormat("fr-FR").format(num) + " FCFA"
  }

  const setArtist = (newArtist: Artist) => {
    mutate(newArtist)
  }

  if (error) return <div className="text-red-400 p-4">Error loading artist</div>
  if (!artist)
    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">Detail Artiste</h1>
          <p className="text-zinc-400 text-sm">ID: {artist.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={() => setShowVerifyDialog(true)} className="text-zinc-300">
              {artist.verified ? (
                <>
                  <XCircle className="w-4 h-4 mr-2" /> Retirer verification
                </>
              ) : (
                <>
                  <CheckCircle className="w-4 h-4 mr-2" /> Verifier
                </>
              )}
            </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>

      {/* Artist Header */}
      <div className="relative rounded-xl overflow-hidden">
        <div
          className="h-48 bg-cover bg-center"
          style={{ backgroundImage: `url(${artist.coverImage || "/placeholder.svg"})` }}
        >
          <div className="absolute inset-0 bg-gradient-to-t from-zinc-900 to-transparent" />
        </div>
        <div className="absolute bottom-0 left-0 right-0 p-6">
          <div className="flex items-end gap-6">
            <img
              src={artist.image || "/placeholder.svg"}
              alt={artist.name}
              className="w-32 h-32 rounded-full border-4 border-zinc-900 object-cover"
            />
            <div className="flex-1 pb-2">
              <div className="flex items-center gap-3 mb-2">
                <h2 className="text-3xl font-bold text-white">{artist.name}</h2>
                {artist.verified && <CheckCircle className="w-6 h-6 text-blue-400 fill-blue-400" />}
              </div>
              <p className="text-zinc-300">{artist.genre}</p>
              <p className="text-zinc-400 text-sm">
                {artist.city}, {artist.country}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-purple-500/20">
              <Users className="w-5 h-5 text-purple-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{formatNumber(artist.monthlyListeners)}</p>
              <p className="text-zinc-400 text-xs">Auditeurs/mois</p>
            </div>
          </div>
        </div>
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-pink-500/20">
              <TrendingUp className="w-5 h-5 text-pink-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{formatNumber(artist.totalStreams)}</p>
              <p className="text-zinc-400 text-xs">Streams totaux</p>
            </div>
          </div>
        </div>
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-blue-500/20">
              <Music className="w-5 h-5 text-blue-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{artist.tracksCount}</p>
              <p className="text-zinc-400 text-xs">Titres</p>
            </div>
          </div>
        </div>
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-green-500/20">
              <Disc3 className="w-5 h-5 text-green-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{artist.albumsCount}</p>
              <p className="text-zinc-400 text-xs">Albums</p>
            </div>
          </div>
        </div>
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-yellow-500/20">
              <DollarSign className="w-5 h-5 text-yellow-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{formatCurrency(artist.earnings.total)}</p>
              <p className="text-zinc-400 text-xs">Revenus totaux</p>
            </div>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <Tabs defaultValue="overview" className="space-y-4">
        <TabsList className="bg-zinc-800/50 border border-zinc-700/50">
          <TabsTrigger value="overview" className="data-[state=active]:bg-purple-600">
            Vue d'ensemble
          </TabsTrigger>
          <TabsTrigger value="tracks" className="data-[state=active]:bg-purple-600">
            Titres
          </TabsTrigger>
          <TabsTrigger value="albums" className="data-[state=active]:bg-purple-600">
            Albums
          </TabsTrigger>
          <TabsTrigger value="earnings" className="data-[state=active]:bg-purple-600">
            Revenus
          </TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-4">
          <div className="grid md:grid-cols-2 gap-4">
            {/* Bio */}
            <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
              <h3 className="font-semibold text-white mb-4">Biographie</h3>
              <p className="text-zinc-400">{artist.bio}</p>
            </div>

            {/* Contact Info */}
            <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
              <h3 className="font-semibold text-white mb-4">Informations</h3>
              <div className="space-y-3">
                <div className="flex items-center gap-3">
                  <Mail className="w-4 h-4 text-zinc-400" />
                  <span className="text-white">{artist.email}</span>
                </div>
                <div className="flex items-center gap-3">
                  <Globe className="w-4 h-4 text-zinc-400" />
                  <a href={artist.website} className="text-purple-400 hover:underline">
                    {artist.website}
                  </a>
                </div>
                <div className="flex items-center gap-3">
                  <Calendar className="w-4 h-4 text-zinc-400" />
                  <span className="text-zinc-400">Inscrit le {artist.joinedDate}</span>
                </div>
              </div>
              <div className="mt-4 pt-4 border-t border-zinc-700/50">
                <h4 className="text-sm font-medium text-zinc-400 mb-2">Reseaux sociaux</h4>
                <div className="flex flex-wrap gap-2">
                  <Badge variant="outline" className="border-zinc-600">
                    {artist.socialLinks.instagram}
                  </Badge>
                  <Badge variant="outline" className="border-zinc-600">
                    {artist.socialLinks.twitter}
                  </Badge>
                  <Badge variant="outline" className="border-zinc-600">
                    {artist.socialLinks.youtube}
                  </Badge>
                </div>
              </div>
            </div>

            {/* Top Tracks */}
            <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4 md:col-span-2">
              <h3 className="font-semibold text-white mb-4">Top 5 Titres</h3>
              <div className="space-y-2">
                {artist.topTracks.map((track: { title: string; album: string; streams: number }, index: number) => (
                  <div
                    key={index}
                    className="flex items-center justify-between p-3 rounded-lg bg-zinc-700/30 hover:bg-zinc-700/50"
                  >
                    <div className="flex items-center gap-4">
                      <span className="text-zinc-400 w-6 text-center">{index + 1}</span>
                      <Play className="w-4 h-4 text-zinc-400" />
                      <div>
                        <p className="text-white font-medium">{track.title}</p>
                        <p className="text-zinc-400 text-sm">{track.album}</p>
                      </div>
                    </div>
                    <span className="text-zinc-400">{formatNumber(track.streams)} streams</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </TabsContent>

        <TabsContent value="tracks" className="space-y-4">
          <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
            <p className="text-zinc-400">Liste complete des {artist.tracksCount} titres de l'artiste...</p>
          </div>
        </TabsContent>

        <TabsContent value="albums" className="space-y-4">
          <div className="grid md:grid-cols-3 gap-4">
            {artist.albums.map(
              (album: { title: string; year: string; tracks: number; streams: number }, index: number) => (
                <div key={index} className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
                  <div className="aspect-square bg-zinc-700/50 rounded-lg mb-3" />
                  <h4 className="font-semibold text-white">{album.title}</h4>
                  <p className="text-zinc-400 text-sm">{album.year}</p>
                  <div className="flex justify-between mt-2 text-sm">
                    <span className="text-zinc-400">{album.tracks} titres</span>
                    <span className="text-purple-400">{formatNumber(album.streams)} streams</span>
                  </div>
                </div>
              ),
            )}
          </div>
        </TabsContent>

        <TabsContent value="earnings" className="space-y-4">
          <div className="grid 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">Revenus totaux</p>
              <p className="text-2xl font-bold text-white">{formatCurrency(artist.earnings.total)}</p>
            </div>
            <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
              <p className="text-zinc-400 text-sm">Ce mois</p>
              <p className="text-2xl font-bold text-green-400">{formatCurrency(artist.earnings.thisMonth)}</p>
            </div>
            <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
              <p className="text-zinc-400 text-sm">Mois dernier</p>
              <p className="text-2xl font-bold text-white">{formatCurrency(artist.earnings.lastMonth)}</p>
            </div>
            <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
              <p className="text-zinc-400 text-sm">En attente</p>
              <p className="text-2xl font-bold text-yellow-400">{formatCurrency(artist.earnings.pending)}</p>
            </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 l'artiste</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Nom de l'artiste</Label>
              <Input defaultValue={artist.name} className="bg-zinc-800 border-zinc-700" />
            </div>
            <div className="space-y-2">
              <Label>Genre</Label>
              <Input defaultValue={artist.genre} className="bg-zinc-800 border-zinc-700" />
            </div>
            <div className="space-y-2">
              <Label>Biographie</Label>
              <Textarea defaultValue={artist.bio} className="bg-zinc-800 border-zinc-700 min-h-24" />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Email</Label>
                <Input defaultValue={artist.email} className="bg-zinc-800 border-zinc-700" />
              </div>
              <div className="space-y-2">
                <Label>Site web</Label>
                <Input defaultValue={artist.website} className="bg-zinc-800 border-zinc-700" />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowEditDialog(false)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={() => setShowEditDialog(false)}>
              Sauvegarder
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Verify Dialog */}
      <Dialog open={showVerifyDialog} onOpenChange={setShowVerifyDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>{artist.verified ? "Retirer la verification" : "Verifier l'artiste"}</DialogTitle>
            <DialogDescription className="text-zinc-400">
              {artist.verified
                ? "La badge de verification sera retiree de cet artiste."
                : "Une badge de verification sera ajoutee a cet artiste."}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowVerifyDialog(false)}>
              Annuler
            </Button>
            <Button
              className="bg-blue-600 hover:bg-blue-700"
              onClick={() => {
                setArtist({ ...artist, verified: !artist.verified })
                setShowVerifyDialog(false)
              }}
            >
              Confirmer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Dialog */}
      <Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle className="text-red-400">Supprimer l'artiste</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Cette action est irreversible. Tous les titres et albums de {artist.name} seront egalement supprimes.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowDeleteDialog(false)}>
              Annuler
            </Button>
            <Button className="bg-red-600 hover:bg-red-700" onClick={() => setShowDeleteDialog(false)}>
              Supprimer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
