"use client"

import { useState } from "react"
import {
  Search,
  MoreHorizontal,
  Play,
  Pause,
  Edit,
  Trash2,
  Eye,
  BarChart2,
  Plus,
  Filter,
  Download,
  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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import Link from "next/link"
import { usePlayer } from "@/components/player-provider"
import { formatDuration } from "@/lib/music-data"
import { useToast } from "@/hooks/use-toast"
import { useAuth } from "@/components/auth-provider"
import useSWR from "swr"

interface Track {
  id: string
  title: string
  album_id: string | null
  album_title?: string
  cover_url: string | null
  audio_url: string | null
  duration_ms: number
  total_streams: number
  status: string
  created_at: string
  genre?: string
  lyrics?: string
}

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

export default function ArtistTracksPage() {
  const { user } = useAuth()
  const { toast } = useToast()
  const { currentTrack, isPlaying, playTrack, togglePlay } = usePlayer()

  const {
    data: tracksData,
    error,
    isLoading,
    mutate,
  } = useSWR<{ data: Track[] }>(user?.artistId ? `/api/tracks?artist_id=${user.artistId}` : null, fetcher)

  const tracks = tracksData?.data || []

  const [searchQuery, setSearchQuery] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [showDetailDialog, setShowDetailDialog] = useState<Track | null>(null)
  const [showStatsDialog, setShowStatsDialog] = useState<Track | null>(null)
  const [showEditDialog, setShowEditDialog] = useState<Track | null>(null)
  const [showDeleteDialog, setShowDeleteDialog] = useState<Track | null>(null)
  const [editForm, setEditForm] = useState({ title: "", genre: "", lyrics: "" })

  const filteredTracks = tracks.filter((track) => {
    const matchesSearch = track.title.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesStatus = statusFilter === "all" || track.status === statusFilter
    return matchesSearch && matchesStatus
  })

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

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

  const getStatusColor = (status: string) => {
    switch (status) {
      case "published":
        return "bg-green-500/10 text-green-400 border-green-500/20"
      case "draft":
        return "bg-zinc-500/10 text-zinc-400 border-zinc-500/20"
      case "pending":
        return "bg-yellow-500/10 text-yellow-400 border-yellow-500/20"
      case "rejected":
        return "bg-red-500/10 text-red-400 border-red-500/20"
      default:
        return "bg-zinc-500/10 text-zinc-400 border-zinc-500/20"
    }
  }

  const handlePlayTrack = (track: Track) => {
    if (!track.audio_url) {
      toast({
        title: "Audio non disponible",
        description: "Ce morceau n'a pas encore de fichier audio.",
        variant: "destructive",
      })
      return
    }
    playTrack({
      id: track.id,
      title: track.title,
      artist: user?.name || "Artiste",
      image: track.cover_url || "/abstract-music-album.png",
      cover_url: track.cover_url,
      album_cover: track.album_cover,
      duration: track.duration_ms / 1000,
      audioUrl: track.audio_url,
    })
  }

  const handleViewDetails = (track: Track) => {
    setShowDetailDialog(track)
  }

  const handleViewStats = (track: Track) => {
    setShowStatsDialog(track)
  }

  const handleEdit = (track: Track) => {
    setEditForm({
      title: track.title,
      genre: track.genre || "",
      lyrics: track.lyrics || "",
    })
    setShowEditDialog(track)
  }

  const handleSaveEdit = async () => {
    if (!showEditDialog) return

    try {
      const response = await fetch(`/api/tracks/${showEditDialog.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(editForm),
      })

      if (response.ok) {
        toast({
          title: "Modifications enregistrees",
          description: `"${editForm.title}" a ete mis a jour.`,
        })
        mutate() // Refresh data
        setShowEditDialog(null)
      } else {
        throw new Error("Failed to update")
      }
    } catch (error) {
      toast({
        title: "Erreur",
        description: "Impossible de sauvegarder les modifications.",
        variant: "destructive",
      })
    }
  }

  const handleDownload = (track: Track) => {
    if (!track.audio_url) {
      toast({
        title: "Telechargement impossible",
        description: "Ce morceau n'a pas de fichier audio.",
        variant: "destructive",
      })
      return
    }

    toast({
      title: "Telechargement lance",
      description: `"${track.title}" est en cours de telechargement.`,
    })

    // Trigger download
    const link = document.createElement("a")
    link.href = track.audio_url
    link.download = `${track.title}.mp3`
    link.click()
  }

  const handlePublish = async (track: Track) => {
    try {
      const response = await fetch(`/api/tracks/${track.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: "pending" }),
      })

      if (response.ok) {
        toast({
          title: "Morceau soumis",
          description: `"${track.title}" a ete soumis pour validation par l'admin.`,
        })
        mutate() // Refresh data
      } else {
        throw new Error("Failed to publish")
      }
    } catch (error) {
      toast({
        title: "Erreur",
        description: "Impossible de soumettre le morceau.",
        variant: "destructive",
      })
    }
  }

  const handleDelete = (track: Track) => {
    setShowDeleteDialog(track)
  }

  const confirmDelete = async () => {
    if (!showDeleteDialog) return

    try {
      const response = await fetch(`/api/tracks/${showDeleteDialog.id}`, {
        method: "DELETE",
      })

      if (response.ok) {
        toast({
          title: "Morceau supprime",
          description: `"${showDeleteDialog.title}" a ete supprime.`,
        })
        mutate() // Refresh data
        setShowDeleteDialog(null)
      } else {
        throw new Error("Failed to delete")
      }
    } catch (error) {
      toast({
        title: "Erreur",
        description: "Impossible de supprimer le morceau.",
        variant: "destructive",
      })
    }
  }

  if (isLoading) {
    return (
      <div className="p-6 flex items-center justify-center min-h-[400px]">
        <Loader2 className="w-8 h-8 text-purple-500 animate-spin" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="p-6 text-center">
        <p className="text-red-400">Erreur lors du chargement des morceaux</p>
        <Button onClick={() => mutate()} className="mt-4">
          Reessayer
        </Button>
      </div>
    )
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Mes Morceaux</h1>
          <p className="text-zinc-400">{tracks.length} morceaux au total</p>
        </div>
        <Link href="/artist/upload">
          <Button className="bg-purple-600 hover:bg-purple-700">
            <Plus className="w-4 h-4 mr-2" />
            Ajouter un morceau
          </Button>
        </Link>
      </div>

      {/* Filters */}
      <div className="flex flex-col gap-4 md: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 morceau..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10 bg-zinc-800/50 border-zinc-700 text-white"
          />
        </div>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-full md:w-48 bg-zinc-800/50 border-zinc-700 text-white">
            <Filter className="w-4 h-4 mr-2" />
            <SelectValue placeholder="Statut" />
          </SelectTrigger>
          <SelectContent className="bg-zinc-800 border-zinc-700">
            <SelectItem value="all">Tous les statuts</SelectItem>
            <SelectItem value="published">Publie</SelectItem>
            <SelectItem value="draft">Brouillon</SelectItem>
            <SelectItem value="pending">En attente</SelectItem>
            <SelectItem value="rejected">Rejete</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Tracks List */}
      {filteredTracks.length === 0 ? (
        <div className="text-center py-12">
          <p className="text-zinc-400 mb-4">Aucun morceau trouve</p>
          <Link href="/artist/upload">
            <Button className="bg-purple-600 hover:bg-purple-700">
              <Plus className="w-4 h-4 mr-2" />
              Ajouter votre premier morceau
            </Button>
          </Link>
        </div>
      ) : (
        <div className="space-y-2">
          {filteredTracks.map((track, index) => {
            const isCurrentTrack = currentTrack?.id === track.id
            return (
              <div
                key={track.id}
                className="flex items-center gap-4 p-3 rounded-lg bg-zinc-800/30 hover:bg-zinc-800/50 transition-colors group"
              >
                <div className="w-8 text-center text-zinc-500 text-sm">{index + 1}</div>

                <div className="relative w-12 h-12 rounded overflow-hidden flex-shrink-0">
                  <img
                    src={track.cover_url || "/placeholder.svg?height=48&width=48&query=music"}
                    alt={track.title}
                    className="w-full h-full object-cover"
                  />
                  <button
                    onClick={() => handlePlayTrack(track)}
                    className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
                  >
                    {isCurrentTrack && isPlaying ? (
                      <Pause className="w-5 h-5 text-white" />
                    ) : (
                      <Play className="w-5 h-5 text-white" />
                    )}
                  </button>
                </div>

                <div className="flex-1 min-w-0">
                  <h3 className="font-medium text-white truncate">{track.title}</h3>
                  <p className="text-sm text-zinc-400 truncate">{track.album_title || "Single"}</p>
                </div>

                <Badge className={`${getStatusColor(track.status)} hidden md:flex`}>
                  {track.status === "published"
                    ? "Publie"
                    : track.status === "draft"
                      ? "Brouillon"
                      : track.status === "pending"
                        ? "En attente"
                        : track.status === "rejected"
                          ? "Rejete"
                          : track.status}
                </Badge>

                <div className="text-zinc-400 text-sm hidden md:block w-24 text-right">
                  {formatStreams(track.total_streams)} streams
                </div>

                <div className="text-zinc-500 text-sm w-12 text-right">{formatDuration(track.duration_ms / 1000)}</div>

                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" size="icon" className="text-zinc-400 hover:text-white">
                      <MoreHorizontal className="w-5 h-5" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end" className="bg-zinc-800 border-zinc-700">
                    <DropdownMenuItem
                      className="text-zinc-300 focus:text-white focus:bg-zinc-700"
                      onClick={() => handleViewDetails(track)}
                    >
                      <Eye className="w-4 h-4 mr-2" />
                      Voir les details
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      className="text-zinc-300 focus:text-white focus:bg-zinc-700"
                      onClick={() => handleViewStats(track)}
                    >
                      <BarChart2 className="w-4 h-4 mr-2" />
                      Statistiques
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      className="text-zinc-300 focus:text-white focus:bg-zinc-700"
                      onClick={() => handleEdit(track)}
                    >
                      <Edit className="w-4 h-4 mr-2" />
                      Modifier
                    </DropdownMenuItem>
                    {(track.status === "draft" || track.status === "rejected") && (
                      <DropdownMenuItem
                        className="text-green-400 focus:text-green-300 focus:bg-zinc-700"
                        onClick={() => handlePublish(track)}
                      >
                        <Play className="w-4 h-4 mr-2" />
                        Soumettre pour validation
                      </DropdownMenuItem>
                    )}
                    <DropdownMenuItem
                      className="text-zinc-300 focus:text-white focus:bg-zinc-700"
                      onClick={() => handleDownload(track)}
                    >
                      <Download className="w-4 h-4 mr-2" />
                      Telecharger
                    </DropdownMenuItem>
                    <DropdownMenuSeparator className="bg-zinc-700" />
                    <DropdownMenuItem
                      className="text-red-400 focus:text-red-300 focus:bg-zinc-700"
                      onClick={() => handleDelete(track)}
                    >
                      <Trash2 className="w-4 h-4 mr-2" />
                      Supprimer
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            )
          })}
        </div>
      )}

      {/* Detail Dialog */}
      <Dialog open={!!showDetailDialog} onOpenChange={() => setShowDetailDialog(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-800 text-white max-w-lg">
          <DialogHeader>
            <DialogTitle>Details du morceau</DialogTitle>
          </DialogHeader>
          {showDetailDialog && (
            <div className="space-y-4">
              <div className="flex gap-4">
                <img
                  src={showDetailDialog.cover_url || "/placeholder.svg?height=120&width=120&query=music"}
                  alt={showDetailDialog.title}
                  className="w-28 h-28 rounded-lg object-cover"
                />
                <div className="flex-1 space-y-2">
                  <h3 className="text-xl font-bold">{showDetailDialog.title}</h3>
                  <p className="text-zinc-400">{showDetailDialog.album_title || "Single"}</p>
                  <Badge className={getStatusColor(showDetailDialog.status)}>
                    {showDetailDialog.status === "published" ? "Publie" : showDetailDialog.status}
                  </Badge>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-zinc-500">Duree:</span>
                  <p className="text-white">{formatDuration(showDetailDialog.duration_ms / 1000)}</p>
                </div>
                <div>
                  <span className="text-zinc-500">Streams:</span>
                  <p className="text-white">{formatStreams(showDetailDialog.total_streams)}</p>
                </div>
                <div>
                  <span className="text-zinc-500">Genre:</span>
                  <p className="text-white">{showDetailDialog.genre || "Non specifie"}</p>
                </div>
                <div>
                  <span className="text-zinc-500">Date d'ajout:</span>
                  <p className="text-white">{new Date(showDetailDialog.created_at).toLocaleDateString("fr-FR")}</p>
                </div>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Stats Dialog */}
      <Dialog open={!!showStatsDialog} onOpenChange={() => setShowStatsDialog(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-800 text-white max-w-lg">
          <DialogHeader>
            <DialogTitle>Statistiques</DialogTitle>
            <DialogDescription className="text-zinc-400">{showStatsDialog?.title}</DialogDescription>
          </DialogHeader>
          {showStatsDialog && (
            <div className="space-y-4">
              <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">Total streams</p>
                  <p className="text-2xl font-bold text-white">{formatStreams(showStatsDialog.total_streams)}</p>
                </div>
                <div className="bg-zinc-800/50 rounded-lg p-4">
                  <p className="text-zinc-400 text-sm">Revenus estimes</p>
                  <p className="text-2xl font-bold text-green-400">
                    {formatCurrency(Math.round(showStatsDialog.total_streams * 0.5))}
                  </p>
                </div>
              </div>
              <div className="bg-zinc-800/50 rounded-lg p-4">
                <p className="text-zinc-400 text-sm mb-2">Performance ce mois</p>
                <div className="h-32 flex items-end gap-1">
                  {Array.from({ length: 30 }, (_, i) => (
                    <div
                      key={i}
                      className="flex-1 bg-purple-500/50 rounded-t"
                      style={{ height: `${Math.random() * 100}%` }}
                    />
                  ))}
                </div>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Edit Dialog */}
      <Dialog open={!!showEditDialog} onOpenChange={() => setShowEditDialog(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-800 text-white">
          <DialogHeader>
            <DialogTitle>Modifier le morceau</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label className="text-zinc-300">Titre</Label>
              <Input
                value={editForm.title}
                onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}
                className="bg-zinc-800/50 border-zinc-700 text-white"
              />
            </div>
            <div className="space-y-2">
              <Label className="text-zinc-300">Genre</Label>
              <Input
                value={editForm.genre}
                onChange={(e) => setEditForm({ ...editForm, genre: e.target.value })}
                className="bg-zinc-800/50 border-zinc-700 text-white"
              />
            </div>
            <div className="space-y-2">
              <Label className="text-zinc-300">Paroles</Label>
              <Textarea
                value={editForm.lyrics}
                onChange={(e) => setEditForm({ ...editForm, lyrics: e.target.value })}
                rows={4}
                className="bg-zinc-800/50 border-zinc-700 text-white"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowEditDialog(null)} className="border-zinc-700 text-zinc-300">
              Annuler
            </Button>
            <Button onClick={handleSaveEdit} className="bg-purple-600 hover:bg-purple-700">
              Enregistrer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog open={!!showDeleteDialog} onOpenChange={() => setShowDeleteDialog(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-800 text-white">
          <DialogHeader>
            <DialogTitle>Confirmer la suppression</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Etes-vous sur de vouloir supprimer "{showDeleteDialog?.title}"? Cette action est irreversible.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowDeleteDialog(null)}
              className="border-zinc-700 text-zinc-300"
            >
              Annuler
            </Button>
            <Button onClick={confirmDelete} className="bg-red-600 hover:bg-red-700">
              Supprimer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
