"use client"

import type React from "react"
import { Play, Pause, Trash2, MoreVertical, Edit, Music } from "lucide-react"
import Link from "next/link"
import { usePlayer } from "@/components/player-provider"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { useState } from "react"

interface MixCardProps {
  id: string
  title: string
  image: string
  href?: string
  tracks?: any[]
  canManage?: boolean
  onDelete?: (id: string) => void
  onEdit?: (id: string) => void
}

export function MixCard({ id, title, image, href, tracks = [], canManage = false, onDelete, onEdit }: MixCardProps) {
  const { playAlbum, currentTrack, isPlaying, togglePlay } = usePlayer()
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)
  const [imageError, setImageError] = useState(false)

  const mixTracks = tracks.map((t) => ({
    id: t.id,
    title: t.title,
    artist: t.artist_name,
    // Priority: track's own cover_url > album_cover > mix image
    image: t.cover_url || t.album_cover || image,
    duration: t.duration || t.duration_ms || 0,
    audioUrl: t.audio_url,
  }))

  const isMixPlaying = mixTracks.some((t) => t.id === currentTrack?.id) && isPlaying

  const hasValidImage = image && image.trim() !== "" && !imageError

  const handlePlay = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (mixTracks.length === 0) return

    if (isMixPlaying) {
      togglePlay()
    } else {
      playAlbum(mixTracks, 0)
    }
  }

  const handleDelete = async () => {
    if (!onDelete) return
    setIsDeleting(true)
    try {
      await onDelete(id)
    } finally {
      setIsDeleting(false)
      setShowDeleteDialog(false)
    }
  }

  const content = (
    <div className="group flex flex-col gap-2">
      <div className="relative h-28 w-28 overflow-hidden rounded-lg">
        {hasValidImage ? (
          <img
            src={image || "/placeholder.svg"}
            alt={title}
            className="h-full w-full object-cover transition-transform group-hover:scale-105"
            onError={() => setImageError(true)}
          />
        ) : (
          <div className="flex h-full w-full items-center justify-center bg-gradient-to-br from-primary/20 to-accent/20">
            <Music className="h-10 w-10 text-primary/50" />
          </div>
        )}
        <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent" />
        <span className="absolute bottom-2 left-2 right-2 text-xs font-medium text-primary-foreground truncate">
          {title}
        </span>

        {canManage && (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button
                onClick={(e) => {
                  e.preventDefault()
                  e.stopPropagation()
                }}
                className="absolute right-1 top-1 flex h-7 w-7 items-center justify-center rounded-full bg-black/50 text-primary-foreground opacity-100 md:opacity-0 transition-opacity md:group-hover:opacity-100 hover:bg-black/70"
              >
                <MoreVertical className="h-4 w-4" />
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-40">
              {onEdit && (
                <DropdownMenuItem onClick={() => onEdit(id)}>
                  <Edit className="mr-2 h-4 w-4" />
                  Modifier
                </DropdownMenuItem>
              )}
              {onDelete && (
                <DropdownMenuItem
                  onClick={() => setShowDeleteDialog(true)}
                  className="text-destructive focus:text-destructive"
                >
                  <Trash2 className="mr-2 h-4 w-4" />
                  Supprimer
                </DropdownMenuItem>
              )}
            </DropdownMenuContent>
          </DropdownMenu>
        )}

        {/* Play button overlay */}
        {mixTracks.length > 0 && !isMixPlaying && (
          <button
            onClick={handlePlay}
            className="absolute right-2 bottom-8 flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground opacity-100 md:opacity-0 shadow-lg transition-opacity md:group-hover:opacity-100 active:scale-95"
          >
            <Play className="h-4 w-4 ml-0.5" />
          </button>
        )}

        {/* Playing indicator */}
        {isMixPlaying && (
          <button
            onClick={handlePlay}
            className="absolute right-2 bottom-8 flex h-8 w-8 items-center justify-center rounded-full bg-primary active:scale-95"
          >
            <Pause className="h-4 w-4" />
          </button>
        )}
      </div>

      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Supprimer ce mix ?</AlertDialogTitle>
            <AlertDialogDescription>
              Cette action est irréversible. Le mix "{title}" sera définitivement supprimé.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeleting}>Annuler</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={isDeleting}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {isDeleting ? "Suppression..." : "Supprimer"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )

  if (href) {
    return <Link href={href}>{content}</Link>
  }

  return content
}
