"use client"

import { useState } from "react"
import { useParams, useRouter } from "next/navigation"
import useSWR from "swr"
import { ArrowLeft, Edit, Trash2, Play, MoreHorizontal, Plus, Save, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"

interface Track {
  id: string
  title: string
  duration: string
  plays: number
}

interface Album {
  id: string
  title: string
  artist_name: string
  cover: string
  type: string
  genre: string
  label: string
  release_date: string
  status: string
  description: string
  streams: number
  total_tracks: number
  total_duration: string
  tracks: Track[]
}

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

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

  const { data: albumData, error, mutate } = useSWR(`/api/albums/${albumId}`, fetcher)
  const album: Album | undefined = albumData?.data

  const [isEditing, setIsEditing] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [showAddTrackDialog, setShowAddTrackDialog] = useState(false)
  const [editForm, setEditForm] = useState({
    title: album?.title || "",
    artist: album?.artist_name || "",
    genre: album?.genre || "",
    release_date: album?.release_date || "",
    description: album?.description || "",
    status: album?.status || "",
  })

  // Update form when album loads
  if (album && editForm.title === "") {
    setEditForm({
      title: album.title,
      artist: album.artist_name,
      genre: album.genre || "",
      release_date: album.release_date || "",
      description: album.description || "",
      status: album.status || "published",
    })
  }

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

  const handleSave = async () => {
    const response = await fetch(`/api/albums/${albumId}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(editForm),
    })

    if (response.ok) {
      mutate()
      setIsEditing(false)
    }
  }

  const handleDelete = async () => {
    const response = await fetch(`/api/albums/${albumId}`, {
      method: "DELETE",
    })

    if (response.ok) {
      router.push("/admin/albums")
    }
  }

  const handleDeleteTrack = async (trackId: string) => {
    const response = await fetch(`/api/tracks/${trackId}`, {
      method: "DELETE",
    })

    if (response.ok) {
      mutate()
    }
  }

  if (error) return <div className="text-red-400 p-4">Error loading album</div>
  if (!album)
    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">{album.title}</h1>
          <p className="text-zinc-400">{album.artist_name}</p>
        </div>
        <div className="flex gap-2">
          {isEditing ? (
            <>
              <Button variant="ghost" onClick={() => setIsEditing(false)}>
                Annuler
              </Button>
              <Button onClick={handleSave} className="bg-purple-600 hover:bg-purple-700">
                <Save className="w-4 h-4 mr-2" />
                Sauvegarder
              </Button>
            </>
          ) : (
            <>
              <Button variant="outline" onClick={() => setIsEditing(true)} className="border-zinc-700">
                <Edit className="w-4 h-4 mr-2" />
                Modifier
              </Button>
              <Button variant="destructive" onClick={() => setShowDeleteDialog(true)}>
                <Trash2 className="w-4 h-4 mr-2" />
                Supprimer
              </Button>
            </>
          )}
        </div>
      </div>

      <div className="grid lg:grid-cols-3 gap-6">
        {/* Album Info */}
        <div className="lg:col-span-1 space-y-4">
          <Card className="bg-zinc-800/30 border-zinc-700/50">
            <CardContent className="p-4">
              <img
                src={album.cover || "/placeholder.svg"}
                alt={album.title}
                className="w-full aspect-square rounded-lg object-cover mb-4"
              />
              {isEditing ? (
                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label>Titre</Label>
                    <Input
                      value={editForm.title}
                      onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}
                      className="bg-zinc-900 border-zinc-700"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Artiste</Label>
                    <Input
                      value={editForm.artist}
                      onChange={(e) => setEditForm({ ...editForm, artist: e.target.value })}
                      className="bg-zinc-900 border-zinc-700"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Genre</Label>
                    <Input
                      value={editForm.genre}
                      onChange={(e) => setEditForm({ ...editForm, genre: e.target.value })}
                      className="bg-zinc-900 border-zinc-700"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Date de sortie</Label>
                    <Input
                      type="date"
                      value={editForm.release_date}
                      onChange={(e) => setEditForm({ ...editForm, release_date: e.target.value })}
                      className="bg-zinc-900 border-zinc-700"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Statut</Label>
                    <Select
                      value={editForm.status}
                      onValueChange={(value) => setEditForm({ ...editForm, status: value })}
                    >
                      <SelectTrigger className="bg-zinc-900 border-zinc-700">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent className="bg-zinc-800 border-zinc-700">
                        <SelectItem value="published">Publie</SelectItem>
                        <SelectItem value="draft">Brouillon</SelectItem>
                        <SelectItem value="scheduled">Planifie</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label>Description</Label>
                    <Textarea
                      value={editForm.description}
                      onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
                      className="bg-zinc-900 border-zinc-700 min-h-20"
                    />
                  </div>
                </div>
              ) : (
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-zinc-400">Type</span>
                    <Badge className="bg-purple-500/20 text-purple-400 border-0">{album.type}</Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-zinc-400">Genre</span>
                    <span className="text-white">{album.genre}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-zinc-400">Label</span>
                    <span className="text-white">{album.label}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-zinc-400">Date de sortie</span>
                    <span className="text-white">{album.release_date}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-zinc-400">Statut</span>
                    <Badge className="bg-green-500/20 text-green-400 border-0">Publie</Badge>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Stats */}
          <Card className="bg-zinc-800/30 border-zinc-700/50">
            <CardHeader className="pb-2">
              <CardTitle className="text-white text-lg">Statistiques</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-zinc-400">Ecoutes totales</span>
                <span className="text-white font-semibold">{formatNumber(album.streams)}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-zinc-400">Titres</span>
                <span className="text-white">{album.total_tracks}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-zinc-400">Duree totale</span>
                <span className="text-white">{album.total_duration}</span>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Tracks List */}
        <div className="lg:col-span-2">
          <Card className="bg-zinc-800/30 border-zinc-700/50">
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="text-white">Titres</CardTitle>
              <Button
                onClick={() => setShowAddTrackDialog(true)}
                size="sm"
                className="bg-purple-600 hover:bg-purple-700"
              >
                <Plus className="w-4 h-4 mr-2" />
                Ajouter
              </Button>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {album.tracks.map((track: Track, index: number) => (
                  <div
                    key={track.id}
                    className="flex items-center gap-4 p-3 rounded-lg hover:bg-zinc-700/30 transition-colors group"
                  >
                    <span className="text-zinc-500 w-6 text-center">{index + 1}</span>
                    <Button
                      size="icon"
                      variant="ghost"
                      className="w-8 h-8 text-zinc-400 hover:text-white opacity-0 group-hover:opacity-100"
                    >
                      <Play className="w-4 h-4" />
                    </Button>
                    <div className="flex-1">
                      <p className="text-white font-medium">{track.title}</p>
                      <p className="text-zinc-400 text-sm">{formatNumber(track.plays)} ecoutes</p>
                    </div>
                    <span className="text-zinc-400 text-sm">{track.duration}</span>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="text-zinc-400 hover:text-white opacity-0 group-hover:opacity-100"
                        >
                          <MoreHorizontal className="w-4 h-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end" className="bg-zinc-800 border-zinc-700">
                        <DropdownMenuItem className="text-zinc-300">
                          <Edit className="w-4 h-4 mr-2" /> Modifier
                        </DropdownMenuItem>
                        <DropdownMenuSeparator className="bg-zinc-700" />
                        <DropdownMenuItem onClick={() => handleDeleteTrack(track.id)} className="text-red-400">
                          <Trash2 className="w-4 h-4 mr-2" /> Supprimer
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Delete 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">
              Etes-vous sur de vouloir supprimer "{album.title}" ? Cette action est irreversible.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowDeleteDialog(false)}>
              Annuler
            </Button>
            <Button variant="destructive" onClick={handleDelete}>
              Supprimer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Add Track Dialog */}
      <Dialog open={showAddTrackDialog} onOpenChange={setShowAddTrackDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Ajouter un titre</DialogTitle>
            <DialogDescription className="text-zinc-400">Ajouter un nouveau titre a cet album</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Titre</Label>
              <Input className="bg-zinc-800 border-zinc-700" placeholder="Nom du titre" />
            </div>
            <div className="space-y-2">
              <Label>Duree</Label>
              <Input className="bg-zinc-800 border-zinc-700" placeholder="3:45" />
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowAddTrackDialog(false)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={() => setShowAddTrackDialog(false)}>
              Ajouter
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
