"use client"

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

type Album = {
  id: string
  title: string
  cover_url: string | null
  album_type: string
  total_tracks: number
  release_date: string | null
  total_streams: number
  status: string
  artist_id: string
  artist_name?: string
  label?: string
  copyright?: string
  is_explicit?: boolean
}

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

export default function ArtistAlbumsPage() {
  const router = useRouter()
  const { user } = useAuth()
  const [showNewAlbum, setShowNewAlbum] = useState(false)
  const [showEditDialog, setShowEditDialog] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [showDetailDialog, setShowDetailDialog] = useState(false)
  const [showTracksDialog, setShowTracksDialog] = useState(false)
  const [selectedAlbum, setSelectedAlbum] = useState<Album | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [coverFile, setCoverFile] = useState<File | null>(null)
  const [newAlbum, setNewAlbum] = useState({
    title: "",
    album_type: "album",
    release_date: "",
    label: "",
    copyright: "",
    is_explicit: false,
  })

  const {
    data: albumsData,
    error,
    isLoading: isFetching,
  } = useSWR(user?.artistId ? `/api/albums?artist_id=${user.artistId}` : null, fetcher)

  const albums: Album[] = albumsData?.data || []

  const getTypeBadge = (type: string) => {
    switch (type) {
      case "album":
        return <Badge className="bg-purple-500/20 text-purple-400 border-0">Album</Badge>
      case "single":
        return <Badge className="bg-blue-500/20 text-blue-400 border-0">Single</Badge>
      case "ep":
        return <Badge className="bg-pink-500/20 text-pink-400 border-0">EP</Badge>
      default:
        return <Badge>{type}</Badge>
    }
  }

  const uploadCover = async (file: File): Promise<string | null> => {
    const formData = new FormData()
    formData.append("file", file)
    formData.append("folder", "covers")

    const res = await fetch("/api/upload", {
      method: "POST",
      body: formData,
    })

    if (!res.ok) return null
    const data = await res.json()
    return data.url
  }

  const handleCreateAlbum = async () => {
    if (!user?.artistId) return
    setIsLoading(true)

    try {
      let coverUrl = null
      if (coverFile) {
        coverUrl = await uploadCover(coverFile)
      }

      const res = await fetch("/api/albums", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...newAlbum,
          artist_id: user.artistId,
          cover_url: coverUrl,
          status: "draft",
        }),
      })

      if (res.ok) {
        mutate(`/api/albums?artist_id=${user.artistId}`)
        setShowNewAlbum(false)
        setNewAlbum({ title: "", album_type: "album", release_date: "", label: "", copyright: "", is_explicit: false })
        setCoverFile(null)
      }
    } catch (error) {
      console.error("Error creating album:", error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleEditAlbum = async () => {
    if (!selectedAlbum || !user?.artistId) return
    setIsLoading(true)

    try {
      let coverUrl = selectedAlbum.cover_url
      if (coverFile) {
        coverUrl = await uploadCover(coverFile)
      }

      const res = await fetch(`/api/albums/${selectedAlbum.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...selectedAlbum,
          cover_url: coverUrl,
        }),
      })

      if (res.ok) {
        mutate(`/api/albums?artist_id=${user.artistId}`)
        setShowEditDialog(false)
        setSelectedAlbum(null)
        setCoverFile(null)
      }
    } catch (error) {
      console.error("Error updating album:", error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleDeleteAlbum = async () => {
    if (!selectedAlbum || !user?.artistId) return
    setIsLoading(true)

    try {
      const res = await fetch(`/api/albums/${selectedAlbum.id}`, {
        method: "DELETE",
      })

      if (res.ok) {
        mutate(`/api/albums?artist_id=${user.artistId}`)
        setShowDeleteDialog(false)
        setSelectedAlbum(null)
      }
    } catch (error) {
      console.error("Error deleting album:", error)
    } finally {
      setIsLoading(false)
    }
  }

  const openEditDialog = (album: Album) => {
    setSelectedAlbum({ ...album })
    setCoverFile(null)
    setShowEditDialog(true)
  }

  const openDeleteDialog = (album: Album) => {
    setSelectedAlbum(album)
    setShowDeleteDialog(true)
  }

  const openDetailDialog = (album: Album) => {
    setSelectedAlbum(album)
    setShowDetailDialog(true)
  }

  const openTracksDialog = (album: Album) => {
    setSelectedAlbum(album)
    setShowTracksDialog(true)
  }

  if (isFetching) {
    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 sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Mes albums</h1>
          <p className="text-zinc-400 text-sm">{albums.length} albums/singles</p>
        </div>
        <Button onClick={() => setShowNewAlbum(true)} className="bg-purple-600 hover:bg-purple-700">
          <Plus className="w-4 h-4 mr-2" />
          Nouvel album
        </Button>
      </div>

      {albums.length === 0 ? (
        <div className="text-center py-16 bg-zinc-800/50 rounded-xl border border-zinc-700/50">
          <Music className="w-16 h-16 mx-auto mb-4 text-zinc-600" />
          <h3 className="text-xl font-medium text-white mb-2">Aucun album</h3>
          <p className="text-zinc-400 mb-6">Commencez par créer votre premier album ou single</p>
          <Button onClick={() => setShowNewAlbum(true)} className="bg-purple-600 hover:bg-purple-700">
            <Plus className="w-4 h-4 mr-2" />
            Créer un album
          </Button>
        </div>
      ) : (
        /* Albums Grid */
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {albums.map((album) => (
            <div
              key={album.id}
              className="bg-zinc-800/50 rounded-xl border border-zinc-700/50 overflow-hidden group hover:border-purple-500/50 transition-all"
            >
              <div className="relative aspect-square">
                <img
                  src={album.cover_url || "/placeholder.svg?height=300&width=300&query=album cover"}
                  alt={album.title}
                  className="w-full h-full object-cover"
                />
                <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                  <Button size="icon" className="w-12 h-12 rounded-full bg-purple-600 hover:bg-purple-700">
                    <Play className="w-6 h-6 fill-white" />
                  </Button>
                </div>
                {album.status === "draft" && (
                  <div className="absolute top-2 left-2">
                    <Badge className="bg-zinc-900/80 text-zinc-300 border-0">Brouillon</Badge>
                  </div>
                )}
              </div>
              <div className="p-4">
                <div className="flex items-start justify-between gap-2">
                  <div className="flex-1 min-w-0">
                    <p className="text-white font-medium truncate">{album.title}</p>
                    <div className="flex items-center gap-2 mt-1">
                      {getTypeBadge(album.album_type || "album")}
                      <span className="text-zinc-400 text-sm">{album.total_tracks || 0} titres</span>
                    </div>
                  </div>
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="text-zinc-400 hover:text-white flex-shrink-0">
                        <MoreHorizontal className="w-4 h-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end" className="bg-zinc-800 border-zinc-700">
                      <DropdownMenuItem onClick={() => openDetailDialog(album)} className="text-zinc-300">
                        <Eye className="w-4 h-4 mr-2" /> Voir
                      </DropdownMenuItem>
                      <DropdownMenuItem onClick={() => openEditDialog(album)} className="text-zinc-300">
                        <Edit className="w-4 h-4 mr-2" /> Modifier
                      </DropdownMenuItem>
                      <DropdownMenuItem onClick={() => openTracksDialog(album)} className="text-zinc-300">
                        <Music className="w-4 h-4 mr-2" /> Gérer les titres
                      </DropdownMenuItem>
                      <DropdownMenuSeparator className="bg-zinc-700" />
                      <DropdownMenuItem onClick={() => openDeleteDialog(album)} className="text-red-400">
                        <Trash2 className="w-4 h-4 mr-2" /> Supprimer
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
                {(album.total_streams || 0) > 0 && (
                  <p className="text-zinc-400 text-sm mt-2">{(album.total_streams || 0).toLocaleString()} streams</p>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* New Album Dialog */}
      <Dialog open={showNewAlbum} onOpenChange={setShowNewAlbum}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Nouvel album</DialogTitle>
            <DialogDescription className="text-zinc-400">Créer un nouvel album ou single</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Pochette</Label>
              <div className="flex items-center gap-4">
                <div className="w-24 h-24 bg-zinc-800 rounded-lg overflow-hidden flex items-center justify-center">
                  {coverFile ? (
                    <img
                      src={URL.createObjectURL(coverFile) || "/placeholder.svg"}
                      alt="Cover preview"
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    <Upload className="w-8 h-8 text-zinc-600" />
                  )}
                </div>
                <div>
                  <Input
                    type="file"
                    accept="image/*"
                    onChange={(e) => setCoverFile(e.target.files?.[0] || null)}
                    className="bg-zinc-800 border-zinc-700"
                  />
                  <p className="text-xs text-zinc-500 mt-1">JPG, PNG. Max 5MB</p>
                </div>
              </div>
            </div>
            <div className="space-y-2">
              <Label>Titre</Label>
              <Input
                value={newAlbum.title}
                onChange={(e) => setNewAlbum({ ...newAlbum, title: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
                placeholder="Nom de l'album"
              />
            </div>
            <div className="space-y-2">
              <Label>Type</Label>
              <Select
                value={newAlbum.album_type}
                onValueChange={(value) => setNewAlbum({ ...newAlbum, album_type: value })}
              >
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="album">Album</SelectItem>
                  <SelectItem value="single">Single</SelectItem>
                  <SelectItem value="ep">EP</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Date de sortie</Label>
              <Input
                type="date"
                value={newAlbum.release_date}
                onChange={(e) => setNewAlbum({ ...newAlbum, release_date: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
              />
            </div>
            <div className="space-y-2">
              <Label>Label</Label>
              <Input
                value={newAlbum.label}
                onChange={(e) => setNewAlbum({ ...newAlbum, label: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
                placeholder="Nom du label (optionnel)"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowNewAlbum(false)} disabled={isLoading}>
              Annuler
            </Button>
            <Button
              className="bg-purple-600 hover:bg-purple-700"
              onClick={handleCreateAlbum}
              disabled={isLoading || !newAlbum.title}
            >
              {isLoading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
              Créer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit Album Dialog */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Modifier l'album</DialogTitle>
            <DialogDescription className="text-zinc-400">Modifiez les informations de l'album</DialogDescription>
          </DialogHeader>
          {selectedAlbum && (
            <div className="space-y-4 py-4">
              <div className="space-y-2">
                <Label>Pochette</Label>
                <div className="flex items-center gap-4">
                  <div className="w-24 h-24 bg-zinc-800 rounded-lg overflow-hidden flex items-center justify-center">
                    {coverFile ? (
                      <img
                        src={URL.createObjectURL(coverFile) || "/placeholder.svg"}
                        alt="Cover preview"
                        className="w-full h-full object-cover"
                      />
                    ) : selectedAlbum.cover_url ? (
                      <img
                        src={selectedAlbum.cover_url || "/placeholder.svg"}
                        alt="Cover"
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <Upload className="w-8 h-8 text-zinc-600" />
                    )}
                  </div>
                  <Input
                    type="file"
                    accept="image/*"
                    onChange={(e) => setCoverFile(e.target.files?.[0] || null)}
                    className="bg-zinc-800 border-zinc-700"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label>Titre</Label>
                <Input
                  value={selectedAlbum.title}
                  onChange={(e) => setSelectedAlbum({ ...selectedAlbum, title: e.target.value })}
                  className="bg-zinc-800 border-zinc-700"
                />
              </div>
              <div className="space-y-2">
                <Label>Type</Label>
                <Select
                  value={selectedAlbum.album_type || "album"}
                  onValueChange={(value) => setSelectedAlbum({ ...selectedAlbum, album_type: value })}
                >
                  <SelectTrigger className="bg-zinc-800 border-zinc-700">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-zinc-800 border-zinc-700">
                    <SelectItem value="album">Album</SelectItem>
                    <SelectItem value="single">Single</SelectItem>
                    <SelectItem value="ep">EP</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Date de sortie</Label>
                <Input
                  type="date"
                  value={selectedAlbum.release_date || ""}
                  onChange={(e) => setSelectedAlbum({ ...selectedAlbum, release_date: e.target.value })}
                  className="bg-zinc-800 border-zinc-700"
                />
              </div>
              <div className="space-y-2">
                <Label>Statut</Label>
                <Select
                  value={selectedAlbum.status}
                  onValueChange={(value) => setSelectedAlbum({ ...selectedAlbum, status: value })}
                >
                  <SelectTrigger className="bg-zinc-800 border-zinc-700">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-zinc-800 border-zinc-700">
                    <SelectItem value="draft">Brouillon</SelectItem>
                    <SelectItem value="published">Publié</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowEditDialog(false)} disabled={isLoading}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleEditAlbum} disabled={isLoading}>
              {isLoading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
              Sauvegarder
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Detail Dialog */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Détails de l'album</DialogTitle>
          </DialogHeader>
          {selectedAlbum && (
            <div className="space-y-4 py-4">
              <div className="flex gap-4">
                <img
                  src={selectedAlbum.cover_url || "/placeholder.svg?height=128&width=128&query=album cover"}
                  alt={selectedAlbum.title}
                  className="w-32 h-32 rounded-lg object-cover"
                />
                <div className="flex-1">
                  <h3 className="text-xl font-bold text-white">{selectedAlbum.title}</h3>
                  <div className="flex items-center gap-2 mt-2">
                    {getTypeBadge(selectedAlbum.album_type || "album")}
                  </div>
                  {selectedAlbum.label && <p className="text-zinc-400 text-sm mt-2">Label: {selectedAlbum.label}</p>}
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4 pt-4 border-t border-zinc-700">
                <div>
                  <p className="text-zinc-400 text-sm">Titres</p>
                  <p className="text-white font-medium">{selectedAlbum.total_tracks || 0}</p>
                </div>
                <div>
                  <p className="text-zinc-400 text-sm">Streams</p>
                  <p className="text-white font-medium">{(selectedAlbum.total_streams || 0).toLocaleString()}</p>
                </div>
                <div>
                  <p className="text-zinc-400 text-sm">Date de sortie</p>
                  <p className="text-white font-medium">{selectedAlbum.release_date || "Non définie"}</p>
                </div>
                <div>
                  <p className="text-zinc-400 text-sm">Statut</p>
                  <p className="text-white font-medium">
                    {selectedAlbum.status === "published" ? "Publié" : "Brouillon"}
                  </p>
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowDetailDialog(false)}>
              Fermer
            </Button>
            <Button
              className="bg-purple-600 hover:bg-purple-700"
              onClick={() => {
                setShowDetailDialog(false)
                if (selectedAlbum) openEditDialog(selectedAlbum)
              }}
            >
              <Edit className="w-4 h-4 mr-2" />
              Modifier
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Manage Tracks Dialog */}
      <Dialog open={showTracksDialog} onOpenChange={setShowTracksDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white max-w-2xl">
          <DialogHeader>
            <DialogTitle>Gérer les titres - {selectedAlbum?.title}</DialogTitle>
            <DialogDescription className="text-zinc-400">Ajoutez ou retirez des titres de cet album</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="flex gap-2">
              <Input className="bg-zinc-800 border-zinc-700 flex-1" placeholder="Rechercher un titre..." />
              <Button className="bg-purple-600 hover:bg-purple-700">
                <Plus className="w-4 h-4 mr-2" />
                Ajouter
              </Button>
            </div>
            <div className="space-y-2 max-h-60 overflow-y-auto">
              {selectedAlbum && (selectedAlbum.total_tracks || 0) > 0 ? (
                Array.from({ length: selectedAlbum.total_tracks || 0 }).map((_, i) => (
                  <div key={i} className="flex items-center gap-3 p-3 bg-zinc-800/50 rounded-lg">
                    <span className="text-zinc-500 w-6 text-center">{i + 1}</span>
                    <div className="w-10 h-10 bg-zinc-700 rounded flex items-center justify-center">
                      <Music className="w-5 h-5 text-zinc-400" />
                    </div>
                    <div className="flex-1">
                      <p className="text-white">Track {i + 1}</p>
                      <p className="text-zinc-400 text-sm">3:45</p>
                    </div>
                    <Button variant="ghost" size="icon" className="text-red-400 hover:text-red-300">
                      <X className="w-4 h-4" />
                    </Button>
                  </div>
                ))
              ) : (
                <div className="text-center py-8 text-zinc-400">
                  <Music className="w-12 h-12 mx-auto mb-2 opacity-50" />
                  <p>Aucun titre dans cet album</p>
                  <p className="text-sm">Commencez par ajouter des titres</p>
                </div>
              )}
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowTracksDialog(false)}>
              Fermer
            </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 l'album</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Êtes-vous sûr de vouloir supprimer "{selectedAlbum?.title}" ? Cette action est irréversible.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowDeleteDialog(false)} disabled={isLoading}>
              Annuler
            </Button>
            <Button variant="destructive" onClick={handleDeleteAlbum} disabled={isLoading}>
              {isLoading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Trash2 className="w-4 h-4 mr-2" />}
              Supprimer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
