/**
 * Composant TrackCard
 * Carte pour afficher une piste avec cover, titre, artiste et actions
 */

import React, { useState } from 'react';
import { Play, Heart, MoreVertical, Music, AlertCircle, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { Track } from '../types/track';
import type { Track as PlayerTrack } from '../../player/types';

export interface TrackCardProps {
  track: Track;
  onPlay?: (track: PlayerTrack) => void;
  onLike?: (track: Track) => void;
  onMore?: (track: Track) => void;
  onClick?: (track: Track) => void;
  isLiked?: boolean;
  isPlaying?: boolean;
  className?: string;
  showActions?: boolean;
  showDuration?: boolean;
  size?: 'sm' | 'md' | 'lg';
}

export function TrackCard({
  track,
  onPlay,
  onLike,
  onMore,
  onClick,
  isLiked = false,
  isPlaying = false,
  className,
  showActions = true,
  showDuration = true,
  size = 'md',
}: TrackCardProps) {
  const [isHovered, setIsHovered] = useState(false);
  const [imageError, setImageError] = useState(false);

  const handlePlay = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (track.status === 'completed' || !track.status) { // Assume completed if no status (legacy)
        const playerTrack: PlayerTrack = {
            id: track.id,
            title: track.title,
            artist: track.artist,
            album: track.album,
            duration: track.duration,
            url: track.stream_manifest_url || '', // Fallback to empty or file_path if direct
            cover: track.cover_art_path,
            genre: track.genre
        };
        onPlay?.(playerTrack);
    }
  };

  // ... (keep existing handlers)

  // ... (keep existing sizeClasses)

  // ... (keep existing formatDuration)

  // Logic to determine what to show in overlay
  const renderOverlayContent = () => {
      if (track.status === 'uploading' || track.status === 'processing') {
          return (
              <div className="flex flex-col items-center justify-center text-white">
                  <Loader2 className={cn("animate-spin mb-1", sizes.icon)} />
                  <span className="text-[10px] font-medium uppercase">Processing</span>
              </div>
          );
      }
      if (track.status === 'failed') {
          return (
              <div className="flex flex-col items-center justify-center text-red-200">
                  <AlertCircle className={cn("mb-1", sizes.icon)} />
                  <span className="text-[10px] font-medium uppercase">Error</span>
              </div>
          );
      }
      
      // Completed / Ready
      if (showActions && onPlay) {
        if (isPlaying) {
            return (
                  <div className="flex items-center gap-1">
                    <div className="w-1 h-3 bg-white rounded-full animate-pulse" style={{ animationDelay: '0ms' }} />
                    <div className="w-1 h-3 bg-white rounded-full animate-pulse" style={{ animationDelay: '150ms' }} />
                    <div className="w-1 h-3 bg-white rounded-full animate-pulse" style={{ animationDelay: '300ms' }} />
                  </div>
            );
        }
        return (
            <Play
                className={cn(
                  'text-white fill-white ml-0.5',
                  sizes.icon
                )}
            />
        );
      }
      return null;
  };

  return (
    <div
      // ... (keep existing className)
      onClick={handleClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      role="button"
      tabIndex={onClick ? 0 : -1}
      aria-label={`Piste: ${track.title}`}
    >
      <div className="flex items-center gap-3">
        {/* Cover */}
        <div className="relative flex-shrink-0">
          <div
            // ... (keep existing div props)
          >
            {track.cover_art_path && !imageError ? (
              <img
                src={track.cover_art_path}
                alt={`Cover de ${track.title}`}
                className={cn(
                  'w-full h-full object-cover transition-transform duration-300',
                  isHovered && 'scale-110'
                )}
                onError={() => setImageError(true)}
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center">
                <Music className={cn('text-gray-400 dark:text-gray-500', sizes.icon)} />
              </div>
            )}
          </div>

          {/* Overlay hover avec gradient */}
          <div
            className={cn(
              'absolute inset-0 rounded-md',
              'bg-gradient-to-t from-black/60 via-black/20 to-transparent',
              'opacity-0 group-hover:opacity-100 transition-opacity duration-300',
              (track.status === 'processing' || track.status === 'uploading' || track.status === 'failed') && 'opacity-100 bg-black/40', // Always show overlay for non-ready states
              'pointer-events-none'
            )}
            aria-hidden="true"
          />

          {/* Play button overlay with animation OR Status */}
          <div
              className={cn(
                'absolute inset-0 flex items-center justify-center',
                'rounded-md transition-all duration-300',
                'opacity-0 group-hover:opacity-100',
                (isPlaying || track.status === 'processing' || track.status === 'uploading' || track.status === 'failed') && 'opacity-100',
                'pointer-events-none'
              )}
            >
              { (showActions && onPlay && track.status === 'completed') || !track.status ? (
                  <button
                    type="button"
                    onClick={handlePlay}
                    className={cn(
                      'flex items-center justify-center',
                      'bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600',
                      'text-white rounded-full shadow-lg',
                      'transition-all duration-300 transform',
                      'hover:scale-110 active:scale-95',
                      'pointer-events-auto',
                      isHovered && 'scale-100',
                      !isHovered && !isPlaying && 'scale-90',
                      sizes.button
                    )}
                    aria-label={`Lire ${track.title}`}
                  >
                    {renderOverlayContent()}
                  </button>
              ) : (
                  // Status display without button wrapper
                  renderOverlayContent()
              )}
            </div>
        </div>

        {/* Track Info - keep existing */}
        <div className="flex-1 min-w-0">
          <div
            className={cn(
              'font-medium text-gray-900 dark:text-white truncate',
              sizes.title
            )}
            title={track.title}
          >
            {track.title}
          </div>
          {track.artist && (
            <div
              className={cn(
                'text-gray-600 dark:text-gray-400 truncate mt-0.5',
                sizes.artist
              )}
              title={track.artist}
            >
              {track.artist}
            </div>
          )}
          {showDuration && (
            <div className={cn('text-gray-500 dark:text-gray-500 mt-0.5', sizes.artist)}>
              {formatDuration(track.duration)}
            </div>
          )}
        </div>

        {/* Actions - keep existing */}
        {showActions && (
          <div
            className={cn(
              'flex items-center gap-1 flex-shrink-0',
              'transition-all duration-300',
              'opacity-0 group-hover:opacity-100',
              'transform translate-x-2 group-hover:translate-x-0'
            )}
          >
            {onLike && (
              <button
                type="button"
                onClick={handleLike}
                className={cn(
                  'p-1.5 rounded-full transition-all duration-200',
                  'text-gray-600 dark:text-gray-400',
                  'hover:bg-gray-100 dark:hover:bg-gray-700',
                  'hover:text-red-500 dark:hover:text-red-400',
                  'hover:scale-110 active:scale-95',
                  isLiked && 'text-red-500 dark:text-red-400',
                  sizes.button
                )}
                aria-label={isLiked ? `Retirer ${track.title} des favoris` : `Ajouter ${track.title} aux favoris`}
                aria-pressed={isLiked}
              >
                <Heart
                  className={cn(
                    sizes.icon,
                    isLiked && 'fill-current',
                    'transition-transform duration-200',
                    'hover:scale-110'
                  )}
                  aria-hidden="true"
                />
                <span className="sr-only">
                  {isLiked ? 'Retirer des favoris' : 'Ajouter aux favoris'}
                </span>
              </button>
            )}

            {onMore && (
              <button
                type="button"
                onClick={handleMore}
                className={cn(
                  'p-1.5 rounded-full transition-all duration-200',
                  'text-gray-600 dark:text-gray-400',
                  'hover:bg-gray-100 dark:hover:bg-gray-700',
                  'hover:scale-110 active:scale-95',
                  sizes.button
                )}
                aria-label={`Plus d'options pour ${track.title}`}
              >
                <MoreVertical
                  className={cn(
                    sizes.icon,
                    'transition-transform duration-200',
                    'hover:rotate-90'
                  )}
                  aria-hidden="true"
                />
                <span className="sr-only">Plus d'options</span>
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

export default TrackCard;

