/**
 * Composant TrackListRow
 * Ligne de piste dans une liste avec hover effects et actions
 */

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

export interface TrackListRowProps {
  track: Track;
  onTrackClick?: (track: Track) => void;
  onTrackPlay?: (track: Track) => void;
  onTrackLike?: (track: Track) => void;
  onTrackMore?: (track: Track) => void;
  onTrackSelect?: (trackId: number, selected: boolean) => void;
  isSelected?: boolean;
  isLiked?: boolean;
  isPlaying?: boolean;
  showCover?: boolean;
  showMetadata?: boolean;
  showDuration?: boolean;
  showActions?: boolean;
  showSelection?: boolean;
  className?: string;
  format?: 'list' | 'table';
}

/**
 * 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 TrackListRow({
  track,
  onTrackClick,
  onTrackPlay,
  onTrackLike,
  onTrackMore,
  onTrackSelect,
  isSelected = false,
  isLiked = false,
  isPlaying = false,
  showCover = true,
  showMetadata = true,
  showDuration = true,
  showActions = true,
  showSelection = false,
  className,
  format = 'list',
}: TrackListRowProps) {
  const [isHovered, setIsHovered] = useState(false);

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

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

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

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

  const handleSelectClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onTrackSelect?.(track.id, !isSelected);
  };

  // Format tableau
  if (format === 'table') {
    return (
      <tr
        className={cn(
          'hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors',
          isSelected && 'bg-blue-50 dark:bg-blue-900/20',
          onTrackClick && 'cursor-pointer'
        )}
        onClick={handleClick}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
        role="row"
        aria-label={`Piste: ${track.title}`}
      >
        {showSelection && (
          <td className="px-4 py-3">
            <input
              type="checkbox"
              checked={isSelected}
              onChange={handleSelectClick as any}
              onClick={(e) => e.stopPropagation()}
              className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              aria-label={`Sélectionner ${track.title}`}
            />
          </td>
        )}
        {showCover && (
          <td className="px-4 py-3">
            <div className="w-10 h-10 flex-shrink-0">
              {track.cover ? (
                <img
                  src={track.cover}
                  alt={`Cover de ${track.title}`}
                  className="w-full h-full rounded-md object-cover"
                />
              ) : (
                <div className="w-full h-full rounded-md bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
                  <Music className="h-5 w-5 text-gray-400 dark:text-gray-500" />
                </div>
              )}
            </div>
          </td>
        )}
        <td className="px-4 py-3 text-sm">
          <div className="font-medium text-gray-900 dark:text-white">
            {track.title}
          </div>
        </td>
        {showMetadata && (
          <td className="px-4 py-3 text-sm">
            <div className="text-gray-600 dark:text-gray-400">
              {track.artist || '-'}
            </div>
          </td>
        )}
        {showMetadata && (
          <td className="px-4 py-3 text-sm">
            <div className="text-gray-600 dark:text-gray-400">
              {track.album || '-'}
            </div>
          </td>
        )}
        {showDuration && (
          <td className="px-4 py-3 text-sm">
            <div className="text-gray-500 dark:text-gray-500">
              {formatDuration(track.duration)}
            </div>
          </td>
        )}
        {showActions && (
          <td className="px-4 py-3">
            <div className="flex items-center justify-end gap-2">
              {onTrackPlay && (isHovered || isPlaying) && (
                <button
                  type="button"
                  onClick={handlePlayClick}
                  className="p-1.5 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                  aria-label={isPlaying ? `Mettre en pause ${track.title}` : `Lire ${track.title}`}
                >
                  {isPlaying ? (
                    <Pause className="h-4 w-4 text-gray-700 dark:text-gray-300" />
                  ) : (
                    <Play className="h-4 w-4 text-gray-700 dark:text-gray-300" />
                  )}
                </button>
              )}
              {onTrackLike && (
                <button
                  type="button"
                  onClick={handleLikeClick}
                  className={cn(
                    'p-1.5 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors',
                    isLiked && 'text-red-500 dark:text-red-400'
                  )}
                  aria-label={isLiked ? `Retirer ${track.title} des favoris` : `Ajouter ${track.title} aux favoris`}
                >
                  <Heart
                    className={cn('h-4 w-4', isLiked && 'fill-current')}
                  />
                </button>
              )}
              {onTrackMore && (
                <button
                  type="button"
                  onClick={handleMoreClick}
                  className="p-1.5 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                  aria-label={`Plus d'options pour ${track.title}`}
                >
                  <MoreVertical className="h-4 w-4 text-gray-700 dark:text-gray-300" />
                </button>
              )}
            </div>
          </td>
        )}
      </tr>
    );
  }

  // Format liste simple
  return (
    <div
      className={cn(
        'flex items-center gap-4 p-3 rounded-lg',
        'hover:bg-gray-100 dark:hover:bg-gray-800',
        'transition-colors cursor-pointer',
        isSelected && 'bg-blue-50 dark:bg-blue-900/20',
        onTrackClick && 'cursor-pointer',
        className
      )}
      onClick={handleClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      role="listitem"
      aria-label={`Piste: ${track.title}`}
    >
      {/* Selection */}
      {showSelection && (
        <div className="flex-shrink-0">
          <input
            type="checkbox"
            checked={isSelected}
            onChange={handleSelectClick as any}
            onClick={(e) => e.stopPropagation()}
            className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            aria-label={`Sélectionner ${track.title}`}
          />
        </div>
      )}

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

      {/* Track Info */}
      <div className="flex-1 min-w-0">
        <div className="font-medium text-gray-900 dark:text-white truncate">
          {track.title}
        </div>
        {showMetadata && track.artist && (
          <div className="text-sm text-gray-600 dark:text-gray-400 truncate">
            {track.artist}
            {track.album && ` • ${track.album}`}
          </div>
        )}
      </div>

      {/* Duration */}
      {showDuration && (
        <div className="text-sm text-gray-500 dark:text-gray-500 flex-shrink-0">
          {formatDuration(track.duration)}
        </div>
      )}

      {/* Actions */}
      {showActions && (
        <div className="flex items-center gap-2 flex-shrink-0">
          {onTrackPlay && (isHovered || isPlaying) && (
            <button
              type="button"
              onClick={handlePlayClick}
              className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
              aria-label={isPlaying ? `Mettre en pause ${track.title}` : `Lire ${track.title}`}
            >
              {isPlaying ? (
                <Pause className="h-5 w-5 text-gray-700 dark:text-gray-300" />
              ) : (
                <Play className="h-5 w-5 text-gray-700 dark:text-gray-300" />
              )}
            </button>
          )}
          {onTrackLike && (
            <button
              type="button"
              onClick={handleLikeClick}
              className={cn(
                'p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors',
                isLiked && 'text-red-500 dark:text-red-400'
              )}
              aria-label={isLiked ? `Retirer ${track.title} des favoris` : `Ajouter ${track.title} aux favoris`}
            >
              <Heart
                className={cn('h-5 w-5', isLiked && 'fill-current')}
              />
            </button>
          )}
          {onTrackMore && (
            <button
              type="button"
              onClick={handleMoreClick}
              className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
              aria-label={`Plus d'options pour ${track.title}`}
            >
              <MoreVertical className="h-5 w-5 text-gray-700 dark:text-gray-300" />
            </button>
          )}
        </div>
      )}
    </div>
  );
}

export default TrackListRow;

