/**
 * Composant pour afficher un track individuel dans une playlist
 * T0473: Create Playlist Track List Component
 */

import { useState } from 'react';
import { Play, Pause, Music, GripVertical } from 'lucide-react';
import { cn } from '@/lib/utils';
import { RemoveTrackButton } from './RemoveTrackButton';
import type { PlaylistTrack, Track } from '../types';

interface PlaylistTrackItemProps {
  playlistTrack: PlaylistTrack;
  track: Track;
  playlistId: string;
  position: number;
  onTrackClick?: (track: Track) => void;
  onTrackPlay?: (track: Track) => void;
  onTrackRemoved?: () => void;
  isPlaying?: boolean;
  className?: string;
  dragHandleProps?: React.HTMLAttributes<HTMLElement>;
  canRemoveTracks?: boolean;
}

/**
 * Formate la durée en MM:SS
 */
function formatDuration(seconds: number): string {
  if (isNaN(seconds) || !isFinite(seconds) || seconds < 0) {
    return '0:00';
  }
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.floor(seconds % 60);
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}

export function PlaylistTrackItem({
  playlistTrack: _playlistTrack,
  track,
  playlistId: _playlistId,
  position,
  onTrackClick,
  onTrackPlay,
  onTrackRemoved,
  isPlaying = false,
  className,
  dragHandleProps,
  canRemoveTracks = true,
}: PlaylistTrackItemProps) {
  const [isHovered, setIsHovered] = useState(false);

  const handleClick = () => {
    onTrackClick?.(track);
  };

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

  return (
    <div
      className={cn(
        'flex items-center gap-2 sm:gap-4 p-2 sm:p-3 rounded-lg',
        'hover:bg-gray-100 dark:hover:bg-gray-800',
        'active:bg-gray-200 dark:active:bg-gray-700',
        'transition-colors touch-manipulation',
        onTrackClick && 'cursor-pointer',
        className,
      )}
      onClick={handleClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      role="listitem"
      aria-label={`Piste ${position}: ${track.title}`}
    >
      {/* Handle de drag (si drag-and-drop est activé) */}
      {dragHandleProps && (
        <div
          {...dragHandleProps}
          className="flex-shrink-0 cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground transition-colors"
          aria-label="Réorganiser"
        >
          <GripVertical className="h-5 w-5" />
        </div>
      )}

      {/* Numéro de position - Mobile optimized */}
      <div className="flex-shrink-0 w-6 sm:w-8 text-center text-xs sm:text-sm text-muted-foreground">
        {isHovered || isPlaying ? (
          <button
            type="button"
            onClick={handlePlayClick}
            className="p-1 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 active:bg-gray-300 dark:active:bg-gray-600 transition-colors touch-manipulation min-h-[32px] min-w-[32px] sm:min-h-0 sm:min-w-0"
            aria-label={
              isPlaying
                ? `Mettre en pause ${track.title}`
                : `Lire ${track.title}`
            }
          >
            {isPlaying ? (
              <Pause className="h-3 w-3 sm:h-4 sm:w-4 text-gray-700 dark:text-gray-300" />
            ) : (
              <Play className="h-3 w-3 sm:h-4 sm:w-4 text-gray-700 dark:text-gray-300" />
            )}
          </button>
        ) : (
          <span>{position}</span>
        )}
      </div>

      {/* Cover - Mobile optimized */}
      <div className="flex-shrink-0">
        {track.cover_art_path ? (
          <img
            src={track.cover_art_path}
            alt={`Cover de ${track.title}`}
            className="w-10 h-10 sm:w-12 sm:h-12 rounded-md object-cover"
          />
        ) : (
          <div className="w-10 h-10 sm:w-12 sm:h-12 rounded-md bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
            <Music className="h-5 w-5 sm:h-6 sm:w-6 text-gray-400 dark:text-gray-500" />
          </div>
        )}
      </div>

      {/* Track Info - Mobile optimized */}
      <div className="flex-1 min-w-0">
        <div className="font-medium text-sm sm:text-base text-gray-900 dark:text-white truncate">
          {track.title}
        </div>
        <div className="text-xs sm:text-sm text-gray-600 dark:text-gray-400 truncate">
          {track.artist}
          {track.album && (
            <span className="hidden sm:inline"> • {track.album}</span>
          )}
        </div>
      </div>

      {/* Duration - Hidden on very small screens */}
      <div className="hidden sm:block text-sm text-gray-500 dark:text-gray-500 flex-shrink-0">
        {formatDuration(track.duration)}
      </div>

      {/* Actions */}
      <div className="flex items-center gap-2 flex-shrink-0">
        {isHovered && canRemoveTracks && onTrackRemoved && (
          <RemoveTrackButton
            onRemove={onTrackRemoved}
            className="h-8 w-8 text-muted-foreground hover:text-destructive"
          />
        )}
      </div>
    </div>
  );
}
