import React from 'react';
import { cn } from '@/lib/utils';
import type { Track } from '../../player/types';
import { LikeButton } from './LikeButton';

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

export function TrackCard({
  track,
  showDuration = true,
  onPlay,
  onMore,
  onClick,
  isLiked,
  isPlaying,
  showActions = true,
  size: _size = 'md',
  className,
}: TrackCardProps) {
  const handlePlay = (e: React.MouseEvent) => {
    e.stopPropagation();
    onPlay?.(track);
  };

  const handleMore = (e: React.MouseEvent) => {
    e.stopPropagation();
    onMore?.(track);
  };

  // Get like_count from track if available (for TrackType)
  const likeCount = (track as any).like_count ?? 0;

  return (
    <div
      role="button"
      tabIndex={onClick ? 0 : -1}
      className={cn(
        'group relative rounded-md overflow-hidden bg-card hover:bg-accent/50 transition-all hover:scale-[1.02] cursor-pointer',
        className,
      )}
      onClick={() => onClick?.(track)}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          onClick?.(track);
        }
      }}
      aria-label={`Piste: ${track.title}`}
    >
      <div className="relative aspect-square overflow-hidden rounded-md">
        {track.cover ? (
          <img
            src={track.cover}
            alt={`Cover de ${track.title}`}
            className="object-cover w-full h-full transition-transform group-hover:scale-105"
            onError={(e) => {
              e.currentTarget.style.display = 'none';
              e.currentTarget.nextElementSibling?.classList.remove('hidden');
            }}
          />
        ) : null}

        {/* Fallback / Placeholder if no cover or error */}
        <div
          className={cn(
            'w-full h-full bg-muted flex items-center justify-center',
            track.cover ? 'hidden' : '',
          )}
        >
          <svg
            className="w-10 h-10 text-muted-foreground"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            aria-hidden="true"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3"
            />
          </svg>
        </div>

        {/* Overlay with Play Button */}
        {(onPlay || isPlaying) && (
          <div
            className={cn(
              'absolute inset-0 bg-black/40 flex items-center justify-center transition-opacity',
              isPlaying ? 'opacity-100' : 'opacity-0 group-hover:opacity-100',
            )}
          >
            <button
              aria-label={
                isPlaying ? `Pause ${track.title}` : `Lire ${track.title}`
              }
              onClick={handlePlay}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  onPlay?.(track);
                }
              }}
              className={cn(
                'rounded-full bg-primary text-primary-foreground p-3 shadow-lg hover:scale-110 transition-transform focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2',
                isPlaying && 'animate-pulse',
              )}
            >
              {isPlaying ? (
                <>
                  <span className="font-bold" aria-hidden="true">
                    ||
                  </span>
                  <span className="sr-only">Pause</span>
                </>
              ) : (
                <>
                  <svg
                    className="w-6 h-6 fill-current"
                    viewBox="0 0 24 24"
                    aria-hidden="true"
                  >
                    <path d="M8 5v14l11-7z" />
                  </svg>
                  <span className="sr-only">Lire</span>
                </>
              )}
            </button>
          </div>
        )}

        {/* Gradient Overlay for Actions */}
        {showActions && (
          <div className="absolute inset-x-0 bottom-0 p-2 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex justify-end gap-2">
            <LikeButton
              trackId={track.id}
              initialLikeCount={likeCount}
              initialIsLiked={isLiked}
              variant="ghost"
              size="icon"
              showCount={false}
              compact
              className="text-white hover:text-red-500"
            />
            <button
              aria-label={`Plus d'options pour ${track.title}`}
              onClick={handleMore}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  onMore?.(track);
                }
              }}
              className="text-white hover:text-primary transition-colors p-1 focus:outline-none focus:ring-2 focus:ring-primary rounded"
            >
              <span aria-hidden="true">•••</span>
              <span className="sr-only">Plus d'options</span>
            </button>
          </div>
        )}
      </div>

      <div className="p-3 space-y-1">
        <h3 className="font-medium leading-none truncate">{track.title}</h3>
        {track.artist && (
          <p className="text-xs text-muted-foreground truncate">
            {track.artist}
          </p>
        )}
        {showDuration && (
          <p className="text-xs text-muted-foreground pt-1">
            {Math.floor(track.duration / 60)}:
            {String(track.duration % 60).padStart(2, '0')}
          </p>
        )}
      </div>
    </div>
  );
}
