"use client"

import { Card } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Play, Pause } from "lucide-react"
import Image from "next/image"
import Link from "next/link"
import { usePlayer } from "./player-provider"
import { useState } from "react"
import { getImageUrl } from "@/lib/image-utils"

interface TrackCardProps {
  id: string
  title: string
  artist: string
  artistId?: string
  coverUrl?: string | null
  album_cover?: string | null
  cover_url?: string | null
  audioUrl: string
  duration?: number
  className?: string
}

export function TrackCard({
  id,
  title,
  artist,
  artistId,
  coverUrl,
  album_cover,
  cover_url,
  audioUrl,
  duration,
  className = "",
}: TrackCardProps) {
  const { currentTrack, isPlaying, playTrack, pauseTrack } = usePlayer()
  const [imageError, setImageError] = useState(false)
  const isCurrentTrack = currentTrack?.id === id

  const getImageSource = (): string => {
    if (imageError) return "/abstract-music-album.png"

    // Priority: track's own cover_url > coverUrl prop > album cover > fallback
    const imageUrl = cover_url || coverUrl || album_cover

    // Use centralized image utility for consistent handling
    return getImageUrl(imageUrl, "track")
  }

  const handlePlayPause = () => {
    if (isCurrentTrack && isPlaying) {
      pauseTrack()
    } else {
      playTrack({
        id,
        title,
        artist,
        audioUrl,
        coverUrl: cover_url || coverUrl || album_cover || undefined,
        duration,
      })
    }
  }

  const displayImageUrl = getImageSource()

  return (
    <Card className={`group relative overflow-hidden bg-card border-border hover:bg-accent transition ${className}`}>
      <Link href={`/track/${id}`} className="block">
        <div className="relative aspect-square">
          <Image
            src={displayImageUrl || "/placeholder.svg"}
            alt={title}
            fill
            className="object-cover"
            unoptimized
            onError={() => setImageError(true)}
          />
          <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition flex items-center justify-center">
            <Button
              size="icon"
              variant="ghost"
              className="h-12 w-12 rounded-full bg-primary hover:bg-primary/80 text-primary-foreground"
              onClick={(e) => {
                e.preventDefault()
                handlePlayPause()
              }}
            >
              {isCurrentTrack && isPlaying ? <Pause className="h-6 w-6" /> : <Play className="h-6 w-6 ml-1" />}
            </Button>
          </div>
        </div>
      </Link>
      <div className="p-4">
        <Link href={`/track/${id}`}>
          <h3 className="font-semibold text-foreground truncate hover:underline">{title}</h3>
        </Link>
        {artistId ? (
          <Link
            href={`/artist/${artistId}`}
            onClick={(e) => e.stopPropagation()}
          >
            <p className="text-sm text-muted-foreground truncate hover:text-primary hover:underline">{artist}</p>
          </Link>
        ) : (
          <p className="text-sm text-muted-foreground truncate">{artist}</p>
        )}
      </div>
    </Card>
  )
}
