/**
 * Composant TrackList
 * Affiche une liste de pistes en format liste avec colonnes, actions et sélection
 */

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

export interface TrackListColumn {
  id: string;
  label: string;
  width?: string;
  sortable?: boolean;
}

export interface TrackListProps extends TrackListBaseProps {
  showCover?: boolean;
  showMetadata?: boolean;
  showDuration?: boolean;
  showActions?: boolean;
  showSelection?: boolean;
  showColumns?: boolean;
  columns?: TrackListColumn[];
  isLoading?: boolean;
  emptyMessage?: string;
  emptyDescription?: string;
  emptyIcon?: 'music' | 'search' | 'filter';
  emptyAction?: React.ReactNode;
  skeletonCount?: number;
  selectedTracks?: number[];
  onTrackSelect?: (trackId: number, selected: boolean) => void;
  onSelectAll?: (selected: boolean) => void;
  onTrackLike?: (track: Track) => void;
  onTrackMore?: (track: Track) => void;
  isLiked?: (trackId: number) => boolean;
  isPlaying?: (trackId: number) => boolean;
  currentPlayingId?: number;
  // Actions groupées pour les pistes sélectionnées
  onSelectedPlay?: (trackIds: number[]) => void;
  onSelectedDelete?: (trackIds: number[]) => void;
  onSelectedLike?: (trackIds: number[]) => void;
  onSelectedDownload?: (trackIds: number[]) => void;
  onSelectedMore?: (trackIds: number[]) => void;
  onClearSelection?: () => void;
  showSelectionActions?: boolean;
  onTrackPlay?: (track: PlayerTrack) => void;
}

export function TrackList({
  tracks,
  onTrackClick,
  onTrackPlay,
  className,
  showCover = true,
  showMetadata = true,
  showDuration = true,
  showActions = true,
  showSelection = false,
  showColumns = false,
  columns,
  isLoading = false,
  emptyMessage,
  emptyDescription,
  emptyIcon,
  emptyAction,
  skeletonCount = 5,
  selectedTracks = [],
  onTrackSelect,
  onSelectAll,
  onTrackLike,
  onTrackMore,
  isLiked,
  isPlaying,
  currentPlayingId,
  onSelectedPlay,
  onSelectedDelete,
  onSelectedLike,
  onSelectedDownload,
  onSelectedMore,
  onClearSelection,
  showSelectionActions = true,
}: TrackListProps) {
  const [hoveredTrackId, setHoveredTrackId] = useState<number | null>(null);

  const defaultColumns: TrackListColumn[] = [
    { id: 'title', label: 'Titre', sortable: true },
    { id: 'artist', label: 'Artiste', sortable: true },
    { id: 'album', label: 'Album', sortable: true },
    { id: 'duration', label: 'Durée', sortable: true },
  ];

  const displayColumns = columns || defaultColumns;
  const allSelected = tracks.length > 0 && selectedTracks.length === tracks.length;
  const someSelected = selectedTracks.length > 0 && selectedTracks.length < tracks.length;

  const handleTrackClick = (track: Track) => {
    onTrackClick?.(track);
  };

  const handlePlayClick = (e: React.MouseEvent, track: Track) => {
    e.stopPropagation();
    if (track.status === 'completed' || !track.status) {
        const playerTrack: PlayerTrack = {
            id: track.id,
            title: track.title,
            artist: track.artist,
            album: track.album,
            duration: track.duration,
            url: track.stream_manifest_url || '', 
            cover: track.cover_art_path,
            genre: track.genre
        };
        onTrackPlay?.(playerTrack);
    }
  };

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

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

  const handleSelectTrack = (e: React.MouseEvent, trackId: number) => {
    e.stopPropagation();
    const isSelected = selectedTracks.includes(trackId);
    onTrackSelect?.(trackId, !isSelected);
  };

  const handleSelectAllClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onSelectAll?.(!allSelected);
  };

  // État de chargement
  if (isLoading) {
    return (
      <TrackListSkeleton
        count={skeletonCount}
        showCover={showCover}
        showMetadata={showMetadata}
        showDuration={showDuration}
        className={className}
      />
    );
  }

  // État vide
  if (tracks.length === 0) {
    return (
      <TrackListEmpty
        message={emptyMessage}
        description={emptyDescription}
        icon={emptyIcon}
        action={emptyAction}
        className={className}
      />
    );
  }

  // Format avec colonnes (table)
  if (showColumns) {
    return (
      <>
        <div className={cn('w-full overflow-x-auto', className)}>
        <table className="w-full border-collapse" role="table" aria-label="Liste de pistes">
          <thead>
            <tr className="border-b border-gray-200 dark:border-gray-700">
              {showSelection && (
                <th className="px-4 py-3 text-left">
                  <input
                    type="checkbox"
                    checked={allSelected}
                    ref={(input) => {
                      if (input) input.indeterminate = someSelected;
                    }}
                    onChange={(e) => handleSelectAllClick(e as any)}
                    className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    aria-label="Sélectionner toutes les pistes"
                  />
                </th>
              )}
              {showCover && (
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider w-16">
                  <span className="sr-only">Cover</span>
                </th>
              )}
              {displayColumns.map((column) => (
                <th
                  key={column.id}
                  className={cn(
                    'px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider',
                    column.width
                  )}
                >
                  {column.label}
                </th>
              ))}
              {showActions && (
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider w-32">
                  <span className="sr-only">Actions</span>
                </th>
              )}
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
            {tracks.map((track) => {
              const isSelected = selectedTracks.includes(track.id);
              const trackIsLiked = isLiked?.(track.id) ?? false;
              const trackIsPlaying = (isPlaying?.(track.id) ?? false) || currentPlayingId === track.id;
              const isHovered = hoveredTrackId === track.id;

              return (
                <tr
                  key={track.id}
                  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={() => handleTrackClick(track)}
                  onMouseEnter={() => setHoveredTrackId(track.id)}
                  onMouseLeave={() => setHoveredTrackId(null)}
                  role="row"
                  aria-label={`Piste: ${track.title}`}
                >
                  {showSelection && (
                    <td className="px-4 py-3">
                      <input
                        type="checkbox"
                        checked={isSelected}
                        onChange={(e) => handleSelectTrack(e as any, track.id)}
                        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_art_path ? (
                          <img
                            src={track.cover_art_path}
                            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>
                  )}
                  {displayColumns.map((column) => (
                    <td key={column.id} className="px-4 py-3 text-sm">
                      {column.id === 'title' && (
                        <div className="font-medium text-gray-900 dark:text-white">
                          {track.title}
                        </div>
                      )}
                      {column.id === 'artist' && (
                        <div className="text-gray-600 dark:text-gray-400">
                          {track.artist || '-'}
                        </div>
                      )}
                      {column.id === 'album' && (
                        <div className="text-gray-600 dark:text-gray-400">
                          {track.album || '-'}
                        </div>
                      )}
                      {column.id === 'duration' && (
                        <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">
                        {(track.status === 'uploading' || track.status === 'processing') && (
                            <div className="flex items-center text-xs text-gray-500 mr-2">
                                <Loader2 className="h-3 w-3 animate-spin mr-1" />
                                Processing
                            </div>
                        )}
                        {track.status === 'failed' && (
                            <div className="flex items-center text-xs text-red-500 mr-2">
                                <AlertCircle className="h-3 w-3 mr-1" />
                                Error
                            </div>
                        )}

                        {onTrackPlay && (track.status === 'completed' || !track.status) && (isHovered || trackIsPlaying) && (
                          <button
                            type="button"
                            onClick={(e) => handlePlayClick(e, track)}
                            className="p-1.5 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                            aria-label={trackIsPlaying ? `Mettre en pause ${track.title}` : `Lire ${track.title}`}
                          >
                            {trackIsPlaying ? (
                              <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={(e) => handleLikeClick(e, track)}
                            className={cn(
                              'p-1.5 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors',
                              trackIsLiked && 'text-red-500 dark:text-red-400'
                            )}
                            aria-label={trackIsLiked ? `Retirer ${track.title} des favoris` : `Ajouter ${track.title} aux favoris`}
                          >
                            <Heart
                              className={cn('h-4 w-4', trackIsLiked && 'fill-current')}
                            />
                          </button>
                        )}
                        {onTrackMore && (
                          <button
                            type="button"
                            onClick={(e) => handleMoreClick(e, track)}
                            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>
              );
            })}
          </tbody>
        </table>
      </div>
      {showSelection && showSelectionActions && selectedTracks.length > 0 && (
        <TrackListSelectionActions
          selectedCount={selectedTracks.length}
          selectedTrackIds={selectedTracks}
          onPlay={onSelectedPlay}
          onDelete={onSelectedDelete}
          onLike={onSelectedLike}
          onDownload={onSelectedDownload}
          onMore={onSelectedMore}
          onClearSelection={onClearSelection}
        />
      )}
      </>
    );
  }

  // Format liste simple (comportement original)
  return (
    <>
      <div className={cn('space-y-2', className)} role="list" aria-label="Liste de pistes">
      {tracks.map((track) => {
        const isSelected = selectedTracks.includes(track.id);
        const trackIsLiked = isLiked?.(track.id) ?? false;
        const trackIsPlaying = (isPlaying?.(track.id) ?? false) || currentPlayingId === track.id;
        const isHovered = hoveredTrackId === track.id;

        return (
          <div
            key={track.id}
            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'
            )}
            onClick={() => handleTrackClick(track)}
            onMouseEnter={() => setHoveredTrackId(track.id)}
            onMouseLeave={() => setHoveredTrackId(null)}
            role="listitem"
            aria-label={`Piste: ${track.title}`}
          >
            {/* Selection */}
            {showSelection && (
              <div className="flex-shrink-0">
                <input
                  type="checkbox"
                  checked={isSelected}
                  onChange={(e) => handleSelectTrack(e as any, track.id)}
                  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_art_path ? (
                  <img
                    src={track.cover_art_path}
                    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">
                
                {(track.status === 'uploading' || track.status === 'processing') && (
                    <div className="flex flex-col items-center justify-center w-10">
                        <Loader2 className="h-5 w-5 animate-spin text-gray-400" />
                    </div>
                )}
                {track.status === 'failed' && (
                    <div className="flex flex-col items-center justify-center w-10">
                        <AlertCircle className="h-5 w-5 text-red-500" />
                    </div>
                )}

                {onTrackPlay && (track.status === 'completed' || !track.status) && (isHovered || trackIsPlaying) && (
                  <button
                    type="button"
                    onClick={(e) => handlePlayClick(e, track)}
                    className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                    aria-label={trackIsPlaying ? `Mettre en pause ${track.title}` : `Lire ${track.title}`}
                  >
                    {trackIsPlaying ? (
                      <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={(e) => handleLikeClick(e, track)}
                    className={cn(
                      'p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors',
                      trackIsLiked && 'text-red-500 dark:text-red-400'
                    )}
                    aria-label={trackIsLiked ? `Retirer ${track.title} des favoris` : `Ajouter ${track.title} aux favoris`}
                  >
                    <Heart
                      className={cn('h-5 w-5', trackIsLiked && 'fill-current')}
                    />
                  </button>
                )}
                {onTrackMore && (
                  <button
                    type="button"
                    onClick={(e) => handleMoreClick(e, track)}
                    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>
        );
      })}
    </div>
    {showSelection && showSelectionActions && selectedTracks.length > 0 && (
      <TrackListSelectionActions
        selectedCount={selectedTracks.length}
        selectedTrackIds={selectedTracks}
        onPlay={onSelectedPlay}
        onDelete={onSelectedDelete}
        onLike={onSelectedLike}
        onDownload={onSelectedDownload}
        onMore={onSelectedMore}
        onClearSelection={onClearSelection}
      />
    )}
    </>
  );
}

/**
 * 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 default TrackList;