"use client"

import type React from "react"

import { useState, useRef } from "react"
import useSWR from "swr"
import { Search, Plus, Edit, Trash2, Eye, Calendar, Music, Loader2, Upload, FileMusic } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
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 { Badge } from "@/components/ui/badge"
import { ConfirmDialog } from "@/components/confirm-dialog"
import { useToast } from "@/hooks/use-toast"

const fetcher = (url: string) => {
  const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null
  return fetch(url, {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  }).then((res) => res.json())
}

export default function AdminAlbumsPage() {
  const { toast } = useToast()
  const [searchQuery, setSearchQuery] = useState("")
  const [typeFilter, setTypeFilter] = useState("all")
  const [showAddAlbum, setShowAddAlbum] = useState(false)
  const [showEditAlbum, setShowEditAlbum] = useState<any | null>(null)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(null)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [showBulkImport, setShowBulkImport] = useState(false)
  const [bulkFiles, setBulkFiles] = useState<File[]>([])
  const [isBulkUploading, setIsBulkUploading] = useState(false)
  const [bulkProgress, setBulkProgress] = useState(0)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const { data, error, isLoading, mutate } = useSWR(`/api/albums?search=${searchQuery}&limit=50`, fetcher)

  const albums = data?.data || []

  // Form state
  const [formData, setFormData] = useState({
    title: "",
    artist_id: "",
    artist_name: "",
    album_type: "album" as "album" | "single" | "ep",
    release_date: "",
    cover_url: "",
  })

  const filteredAlbums = albums.filter((album: any) => {
    const matchesType = typeFilter === "all" || album.album_type === typeFilter
    return matchesType
  })

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

  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-cyan-500/20 text-cyan-400 border-0">EP</Badge>
      default:
        return <Badge>{type}</Badge>
    }
  }

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

  const handleAddAlbum = async () => {
    if (!formData.title) return

    setIsSubmitting(true)
    try {
      const res = await fetch("/api/albums", {
        method: "POST",
        headers: getAuthHeaders(),
        body: JSON.stringify({
          title: formData.title,
          artist_id: formData.artist_id || null,
          album_type: formData.album_type,
          release_date: formData.release_date || null,
          cover_url: formData.cover_url || null,
          status: "published",
        }),
      })

      if (res.ok) {
        toast({ title: "Album créé", description: "L'album a été ajouté avec succès" })
        mutate()
        setShowAddAlbum(false)
        resetForm()
      } else {
        const error = await res.json()
        toast({ title: "Erreur", description: error.error, variant: "destructive" })
      }
    } catch (err) {
      toast({ title: "Erreur", description: "Une erreur est survenue", variant: "destructive" })
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleEditAlbum = async () => {
    if (!showEditAlbum) return

    setIsSubmitting(true)
    try {
      const res = await fetch(`/api/albums/${showEditAlbum.id}`, {
        method: "PATCH",
        headers: getAuthHeaders(),
        body: JSON.stringify({
          title: formData.title,
          album_type: formData.album_type,
          release_date: formData.release_date || null,
        }),
      })

      if (res.ok) {
        toast({ title: "Album mis à jour", description: "Les modifications ont été enregistrées" })
        mutate()
        setShowEditAlbum(null)
        resetForm()
      } else {
        const error = await res.json()
        toast({ title: "Erreur", description: error.error, variant: "destructive" })
      }
    } catch (err) {
      toast({ title: "Erreur", description: "Une erreur est survenue", variant: "destructive" })
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleDeleteAlbum = async (id: string) => {
    try {
      const token = localStorage.getItem("auth_token")
      const res = await fetch(`/api/albums/${id}`, {
        method: "DELETE",
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      })

      if (res.ok) {
        toast({ title: "Album supprimé", description: "L'album a été supprimé avec succès" })
        mutate()
      } else {
        toast({ title: "Erreur", description: "Impossible de supprimer l'album", variant: "destructive" })
      }
    } catch (err) {
      toast({ title: "Erreur", description: "Une erreur est survenue", variant: "destructive" })
    }
    setShowDeleteConfirm(null)
  }

  const handleBulkFilesSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || [])
    const audioFiles = files.filter((f) => f.type.startsWith("audio/"))
    setBulkFiles(audioFiles)
  }

  const handleBulkImport = async () => {
    if (bulkFiles.length === 0 || !formData.title) return

    setIsBulkUploading(true)
    setBulkProgress(0)

    try {
      const token = localStorage.getItem("auth_token")

      // 1. Create the album first
      const albumRes = await fetch("/api/albums", {
        method: "POST",
        headers: getAuthHeaders(),
        body: JSON.stringify({
          title: formData.title,
          artist_id: formData.artist_id || null,
          album_type: formData.album_type,
          release_date: formData.release_date || null,
          status: "published",
        }),
      })

      if (!albumRes.ok) {
        throw new Error("Failed to create album")
      }

      const album = await albumRes.json()
      setBulkProgress(10)

      // 2. Upload each track
      for (let i = 0; i < bulkFiles.length; i++) {
        const file = bulkFiles[i]
        const trackTitle = file.name.replace(/\.[^/.]+$/, "").replace(/^\d+[\s._-]*/, "")

        // Upload audio file using chunked upload
        const formDataUpload = new FormData()
        formDataUpload.append("file", file)
        formDataUpload.append("folder", "audio")

        // Use the chunked upload for large files
        const uploadRes = await fetch("/api/upload/audio/chunk", {
          method: "POST",
          headers: token ? { Authorization: `Bearer ${token}` } : {},
          body: (() => {
            const fd = new FormData()
            fd.append("chunk", file)
            fd.append("chunkIndex", "0")
            fd.append("totalChunks", "1")
            fd.append("fileName", file.name)
            fd.append("fileType", file.type)
            fd.append("uploadId", `bulk-${Date.now()}-${i}`)
            return fd
          })(),
        })

        if (!uploadRes.ok) {
          console.error(`Failed to upload track ${i + 1}`)
          continue
        }

        const uploadData = await uploadRes.json()

        // Create track record
        await fetch("/api/admin/tracks", {
          method: "POST",
          headers: getAuthHeaders(),
          body: JSON.stringify({
            title: trackTitle,
            album_id: album.id,
            artist_id: formData.artist_id || null,
            audio_url: uploadData.url,
            duration: 0,
            track_number: i + 1,
            status: "published",
          }),
        })

        setBulkProgress(10 + Math.round(((i + 1) / bulkFiles.length) * 90))
      }

      toast({
        title: "Import terminé",
        description: `${bulkFiles.length} titres ajoutés à l'album "${formData.title}"`,
      })
      mutate()
      setShowBulkImport(false)
      setBulkFiles([])
      resetForm()
    } catch (err) {
      console.error("Bulk import error:", err)
      toast({ title: "Erreur", description: "Erreur lors de l'import", variant: "destructive" })
    } finally {
      setIsBulkUploading(false)
      setBulkProgress(0)
    }
  }

  const resetForm = () => {
    setFormData({ title: "", artist_id: "", artist_name: "", album_type: "album", release_date: "", cover_url: "" })
  }

  const openEditDialog = (album: any) => {
    setFormData({
      title: album.title,
      artist_id: album.artist_id || "",
      artist_name: album.artist_name || "",
      album_type: album.album_type || "album",
      release_date: album.release_date?.split("T")[0] || "",
      cover_url: album.cover_url || "",
    })
    setShowEditAlbum(album)
  }

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

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[400px] text-center">
        <p className="text-red-400 mb-4">Erreur lors du chargement des albums</p>
        <Button onClick={() => mutate()}>Réessayer</Button>
      </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">Albums</h1>
          <p className="text-zinc-400 text-sm">{data?.total || 0} albums au total</p>
        </div>
        <div className="flex gap-2">
          <Button onClick={() => setShowBulkImport(true)} variant="outline" className="border-zinc-700">
            <Upload className="w-4 h-4 mr-2" />
            Import en masse
          </Button>
          <Button onClick={() => setShowAddAlbum(true)} className="bg-purple-600 hover:bg-purple-700">
            <Plus className="w-4 h-4 mr-2" />
            Ajouter un album
          </Button>
        </div>
      </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 album ou artiste..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10 bg-zinc-800/50 border-zinc-700 text-white"
          />
        </div>
        <Select value={typeFilter} onValueChange={setTypeFilter}>
          <SelectTrigger className="w-full sm:w-40 bg-zinc-800/50 border-zinc-700 text-white">
            <SelectValue placeholder="Type" />
          </SelectTrigger>
          <SelectContent className="bg-zinc-800 border-zinc-700">
            <SelectItem value="all">Tous les types</SelectItem>
            <SelectItem value="album">Album</SelectItem>
            <SelectItem value="single">Single</SelectItem>
            <SelectItem value="ep">EP</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Albums Grid */}
      {filteredAlbums.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-12 text-center">
          <Music className="w-12 h-12 text-zinc-600 mb-4" />
          <h3 className="text-lg font-medium text-white mb-2">Aucun album</h3>
          <p className="text-zinc-400 mb-4">Commencez par ajouter un album</p>
          <Button onClick={() => setShowAddAlbum(true)} className="bg-purple-600 hover:bg-purple-700">
            <Plus className="w-4 h-4 mr-2" />
            Ajouter un album
          </Button>
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {filteredAlbums.map((album: any) => (
            <div
              key={album.id}
              className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 overflow-hidden hover:bg-zinc-800/50 transition-colors group"
            >
              <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/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
                  <Button size="icon" variant="ghost" className="text-white hover:bg-white/20">
                    <Eye className="w-5 h-5" />
                  </Button>
                  <Button
                    size="icon"
                    variant="ghost"
                    className="text-white hover:bg-white/20"
                    onClick={() => openEditDialog(album)}
                  >
                    <Edit className="w-5 h-5" />
                  </Button>
                  <Button
                    size="icon"
                    variant="ghost"
                    className="text-red-400 hover:bg-red-400/20"
                    onClick={() => setShowDeleteConfirm(album.id)}
                  >
                    <Trash2 className="w-5 h-5" />
                  </Button>
                </div>
              </div>
              <div className="p-4">
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0">
                    <h3 className="font-semibold text-white truncate">{album.title}</h3>
                    <p className="text-sm text-zinc-400 truncate">{album.artist_name || "Artiste inconnu"}</p>
                  </div>
                  {getTypeBadge(album.album_type)}
                </div>
                <div className="flex items-center justify-between mt-3 pt-3 border-t border-zinc-700/50 text-xs text-zinc-400">
                  <span className="flex items-center gap-1">
                    <Music className="w-3 h-3" /> {album.track_count || 0} titres
                  </span>
                  <span className="flex items-center gap-1">
                    <Calendar className="w-3 h-3" /> {album.release_date?.split("-")[0] || "N/A"}
                  </span>
                </div>
                <p className="text-sm text-purple-400 mt-2">{formatStreams(album.total_streams || 0)} streams</p>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Add Album Dialog */}
      <Dialog open={showAddAlbum} onOpenChange={setShowAddAlbum}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Ajouter un album</DialogTitle>
            <DialogDescription className="text-zinc-400">Créer un nouvel album</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Titre de l'album</Label>
              <Input
                className="bg-zinc-800 border-zinc-700"
                placeholder="Titre"
                value={formData.title}
                onChange={(e) => setFormData((prev) => ({ ...prev, title: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Type</Label>
                <Select
                  value={formData.album_type}
                  onValueChange={(v) =>
                    setFormData((prev) => ({ ...prev, album_type: v as typeof formData.album_type }))
                  }
                >
                  <SelectTrigger className="bg-zinc-800 border-zinc-700">
                    <SelectValue placeholder="Type" />
                  </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"
                  className="bg-zinc-800 border-zinc-700"
                  value={formData.release_date}
                  onChange={(e) => setFormData((prev) => ({ ...prev, release_date: e.target.value }))}
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowAddAlbum(false)}>
              Annuler
            </Button>
            <Button
              className="bg-purple-600 hover:bg-purple-700"
              onClick={handleAddAlbum}
              disabled={!formData.title || isSubmitting}
            >
              {isSubmitting ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
              Créer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit Album Dialog */}
      <Dialog open={!!showEditAlbum} onOpenChange={() => setShowEditAlbum(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Modifier l'album</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>Titre de l'album</Label>
              <Input
                className="bg-zinc-800 border-zinc-700"
                value={formData.title}
                onChange={(e) => setFormData((prev) => ({ ...prev, title: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Type</Label>
                <Select
                  value={formData.album_type}
                  onValueChange={(v) =>
                    setFormData((prev) => ({ ...prev, album_type: v as typeof formData.album_type }))
                  }
                >
                  <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"
                  className="bg-zinc-800 border-zinc-700"
                  value={formData.release_date}
                  onChange={(e) => setFormData((prev) => ({ ...prev, release_date: e.target.value }))}
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowEditAlbum(null)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleEditAlbum} disabled={isSubmitting}>
              {isSubmitting ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
              Enregistrer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

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

      <Dialog open={showBulkImport} onOpenChange={setShowBulkImport}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white max-w-2xl">
          <DialogHeader>
            <DialogTitle>Import en masse</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Créez un album et importez plusieurs titres en une fois
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Titre de l'album</Label>
              <Input
                className="bg-zinc-800 border-zinc-700"
                placeholder="Nom de l'album"
                value={formData.title}
                onChange={(e) => setFormData((prev) => ({ ...prev, title: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Type</Label>
                <Select
                  value={formData.album_type}
                  onValueChange={(v) =>
                    setFormData((prev) => ({ ...prev, album_type: v as typeof formData.album_type }))
                  }
                >
                  <SelectTrigger className="bg-zinc-800 border-zinc-700">
                    <SelectValue placeholder="Type" />
                  </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"
                  className="bg-zinc-800 border-zinc-700"
                  value={formData.release_date}
                  onChange={(e) => setFormData((prev) => ({ ...prev, release_date: e.target.value }))}
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label>Fichiers audio</Label>
              <div
                onClick={() => fileInputRef.current?.click()}
                className="border-2 border-dashed border-zinc-700 rounded-lg p-8 text-center cursor-pointer hover:border-purple-500 transition-colors"
              >
                <input
                  ref={fileInputRef}
                  type="file"
                  multiple
                  accept="audio/*"
                  onChange={handleBulkFilesSelect}
                  className="hidden"
                />
                <FileMusic className="w-12 h-12 mx-auto mb-4 text-zinc-500" />
                <p className="text-zinc-300 mb-2">Cliquez pour sélectionner des fichiers audio</p>
                <p className="text-sm text-zinc-500">MP3, WAV, FLAC... (plusieurs fichiers)</p>
              </div>

              {bulkFiles.length > 0 && (
                <div className="mt-4 space-y-2">
                  <p className="text-sm text-zinc-400">{bulkFiles.length} fichier(s) sélectionné(s):</p>
                  <div className="max-h-40 overflow-y-auto space-y-1">
                    {bulkFiles.map((file, i) => (
                      <div
                        key={i}
                        className="flex items-center gap-2 text-sm text-zinc-300 bg-zinc-800 rounded px-3 py-2"
                      >
                        <Music className="w-4 h-4 text-purple-400" />
                        <span className="truncate">{file.name}</span>
                        <span className="text-zinc-500 ml-auto">{(file.size / 1024 / 1024).toFixed(1)} MB</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {isBulkUploading && (
                <div className="mt-4">
                  <div className="flex items-center justify-between text-sm text-zinc-400 mb-2">
                    <span>Import en cours...</span>
                    <span>{bulkProgress}%</span>
                  </div>
                  <div className="h-2 bg-zinc-800 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-purple-600 transition-all duration-300"
                      style={{ width: `${bulkProgress}%` }}
                    />
                  </div>
                </div>
              )}
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowBulkImport(false)} disabled={isBulkUploading}>
              Annuler
            </Button>
            <Button
              className="bg-purple-600 hover:bg-purple-700"
              onClick={handleBulkImport}
              disabled={!formData.title || bulkFiles.length === 0 || isBulkUploading}
            >
              {isBulkUploading ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin mr-2" />
                  Import...
                </>
              ) : (
                <>
                  <Upload className="w-4 h-4 mr-2" />
                  Importer {bulkFiles.length} titre(s)
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
