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

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

export interface TrackListProps {
  tracks: Track[];
  isLoading?: boolean;
  emptyMessage?: string;
  onTrackClick?: (track: Track) => void;
  onTrackPlay?: (track: Track) => void;
  showCover?: boolean;
  showMetadata?: boolean;
  showDuration?: boolean;
  className?: string;
  showColumns?: boolean;
  columns?: TrackListColumn[];
  showSelection?: boolean;
  onTrackSelect?: (id: string, selected: boolean) => void;
  onSelectAll?: () => void;
  selectedTracks?: string[];
  onTrackLike?: (track: Track) => void;
  isLiked?: (id: string) => boolean;
  currentPlayingId?: string | null;
  onTrackMore?: (track: Track) => void;
  showSelectionActions?: boolean;
  onSelectedPlay?: (ids: string[]) => void;
  onClearSelection?: () => void;
}

export function TrackList({
  tracks,
  isLoading,
  emptyMessage = 'Aucune piste disponible',
  onTrackClick,
  onTrackPlay,
  showCover = true,
  showMetadata = true,
  showDuration = true,
  className,
  showColumns,
  columns,
  showSelection,
  onTrackSelect,
  onSelectAll,
  selectedTracks = [],
  onTrackLike,
  isLiked,
  currentPlayingId,
  onTrackMore,
  showSelectionActions = true,
  onSelectedPlay,
  onClearSelection,
}: TrackListProps) {
  if (isLoading) {
    return (
      <div
        role="status"
        aria-label="Chargement des pistes"
        className="p-4 text-center"
      >
        Loading...
      </div>
    );
  }

  if (tracks.length === 0) {
    return (
      <div className="p-4 text-center text-muted-foreground">
        <p>{emptyMessage}</p>
      </div>
    );
  }

  const allSelected =
    tracks.length > 0 && selectedTracks.length === tracks.length;

  return (
    <div className={cn('space-y-4', className)}>
      {showSelection && showSelectionActions && selectedTracks.length > 0 && (
        <div className="flex items-center gap-2 p-2 bg-muted rounded-md mb-2">
          <span>{selectedTracks.length} pistes sélectionnées</span>
          <button
            aria-label="Lire les pistes sélectionnées"
            onClick={() => onSelectedPlay?.(selectedTracks)}
          >
            Play
          </button>
          <button
            aria-label="Désélectionner toutes les pistes"
            onClick={onClearSelection}
          >
            Clear
          </button>
        </div>
      )}

      {showColumns ? (
        <table className="w-full text-sm">
          <thead>
            <tr>
              {showSelection && (
                <th className="w-8">
                  <input
                    type="checkbox"
                    checked={allSelected}
                    onChange={onSelectAll}
                    aria-label="Select all"
                  />
                </th>
              )}
              {columns ? (
                columns.map((col) => <th key={col.id}>{col.label}</th>)
              ) : (
                <>
                  <th className="text-left py-2">Titre</th>
                  <th className="text-left py-2">Artiste</th>
                </>
              )}
            </tr>
          </thead>
          <tbody role="list">
            {tracks.map((track) => (
              <tr
                key={track.id}
                role="listitem"
                className={cn(
                  selectedTracks.includes(track.id) &&
                    'bg-blue-50 dark:bg-blue-900/20',
                )}
              >
                {showSelection && (
                  <td>
                    <input
                      type="checkbox"
                      checked={selectedTracks.includes(track.id)}
                      onChange={(e) =>
                        onTrackSelect?.(track.id, e.target.checked)
                      }
                    />
                  </td>
                )}
                <td>{track.title}</td>
                <td>{track.artist}</td>
              </tr>
            ))}
          </tbody>
        </table>
      ) : (
        <ul role="list" className="space-y-1">
          {tracks.map((track) => (
            <li
              key={track.id}
              role="listitem"
              className={cn(
                'flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 group h-14',
                selectedTracks.includes(track.id) &&
                  'bg-blue-50 dark:bg-blue-900/20',
              )}
              onClick={() => onTrackClick?.(track)}
            >
              {showSelection && (
                <input
                  type="checkbox"
                  checked={selectedTracks.includes(track.id)}
                  onChange={(e) => {
                    e.stopPropagation();
                    onTrackSelect?.(track.id, e.target.checked);
                  }}
                  onClick={(e) => e.stopPropagation()}
                />
              )}

              {/* Cover/Play Button */}
              <div className="relative w-10 h-10 flex-shrink-0">
                {showCover && track.cover && (
                  <img
                    src={track.cover}
                    alt={`Cover de ${track.title}`}
                    className="w-full h-full object-cover rounded"
                  />
                )}
                {/* Play Overlay */}
                <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 bg-black/40 transition-opacity">
                  {currentPlayingId === track.id ? (
                    <button
                      aria-label="Mettre en pause"
                      onClick={(e) => {
                        e.stopPropagation();
                        onTrackPlay?.(track);
                      }}
                    >
                      II
                    </button>
                  ) : (
                    <button
                      aria-label="Lire"
                      onClick={(e) => {
                        e.stopPropagation();
                        onTrackPlay?.(track);
                      }}
                    >
                      ▶
                    </button>
                  )}
                </div>
              </div>

              <div className="flex-1 min-w-0">
                <div className="font-medium truncate">{track.title}</div>
                {showMetadata && (
                  <div className="text-xs text-muted-foreground truncate">
                    {track.artist}
                  </div>
                )}
              </div>

              {showDuration && (
                <div className="text-xs text-muted-foreground">
                  {Math.floor(track.duration / 60)}:
                  {String(track.duration % 60).padStart(2, '0')}
                </div>
              )}

              {/* Actions */}
              <div className="opacity-0 group-hover:opacity-100 flex gap-2">
                <button
                  aria-label={
                    isLiked?.(track.id)
                      ? 'Retirer des favoris'
                      : 'Ajouter aux favoris'
                  }
                  onClick={(e) => {
                    e.stopPropagation();
                    onTrackLike?.(track);
                  }}
                >
                  {isLiked?.(track.id) ? '♥' : '♡'}
                </button>
                <button
                  aria-label="Plus d'options"
                  onClick={(e) => {
                    e.stopPropagation();
                    onTrackMore?.(track);
                  }}
                >
                  ...
                </button>
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
