/**
 * Composant TrackListContainer
 * Intégration finale de tous les composants de la liste de pistes
 * Assemble TrackFilters, TrackSort, ViewToggle, TrackList/TrackGrid, Pagination
 */

import React, { useState, useMemo } from 'react';
import { cn } from '@/lib/utils';
import { useTrackList } from '../hooks/useTrackList';
import { TrackFilters } from './TrackFilters';
import { TrackSort } from './TrackSort';
import { ViewToggle } from './ViewToggle';
import { TrackList } from './TrackList';
import { TrackGrid } from './TrackGrid';
import { TrackListPagination } from './TrackListPagination';
import { TrackListEmpty } from './TrackListEmpty';
import type { UseTrackListOptions } from '../hooks/useTrackList';
import type { Track } from '../../player/types';
import type { TrackListDisplayMode } from '../types';

export interface TrackListContainerProps {
  // Options pour useTrackList
  useService?: boolean;
  autoLoad?: boolean;
  persistFilters?: boolean;
  persistSort?: boolean;
  syncUrlParams?: boolean;
  storageKeyPrefix?: string;
  initialTracks?: Track[];
  initialDisplayMode?: TrackListDisplayMode;
  
  // Options d'affichage
  showFilters?: boolean;
  showSort?: boolean;
  showViewToggle?: boolean;
  showPagination?: boolean;
  showSelection?: boolean;
  
  // Options pour les filtres
  availableGenres?: string[];
  availableArtists?: string[];
  availableYears?: number[];
  
  // Options pour la grille
  gridColumns?: 2 | 3 | 4 | 5 | 6;
  showDensitySelector?: boolean;
  
  // Callbacks
  onTrackClick?: (track: Track) => void;
  onTrackPlay?: (track: Track) => void;
  onTrackLike?: (track: Track) => void;
  onTrackMore?: (track: Track) => void;
  isLiked?: (trackId: number) => boolean;
  isPlaying?: (trackId: number) => boolean;
  currentPlayingId?: number;
  
  // Actions groupées
  onSelectedPlay?: (trackIds: number[]) => void;
  onSelectedDelete?: (trackIds: number[]) => void;
  onSelectedLike?: (trackIds: number[]) => void;
  onSelectedDownload?: (trackIds: number[]) => void;
  onSelectedMore?: (trackIds: number[]) => void;
  
  className?: string;
}

export function TrackListContainer({
  useService = true,
  autoLoad = true,
  persistFilters = false,
  persistSort = false,
  syncUrlParams = false,
  storageKeyPrefix = 'trackList',
  initialTracks = [],
  initialDisplayMode = 'list',
  showFilters = true,
  showSort = true,
  showViewToggle = true,
  showPagination = true,
  showSelection = false,
  availableGenres = [],
  availableArtists = [],
  availableYears = [],
  gridColumns = 4,
  showDensitySelector = false,
  onTrackClick,
  onTrackPlay,
  onTrackLike,
  onTrackMore,
  isLiked,
  isPlaying,
  currentPlayingId,
  onSelectedPlay,
  onSelectedDelete,
  onSelectedLike,
  onSelectedDownload,
  onSelectedMore,
  className,
}: TrackListContainerProps) {
  const [selectedTracks, setSelectedTracks] = useState<number[]>([]);

  // Options pour useTrackList
  const trackListOptions: UseTrackListOptions = {
    initialTracks,
    initialDisplayMode,
    useService,
    autoLoad,
    persistFilters,
    persistSort,
    syncUrlParams,
    storageKeyPrefix,
  };

  const trackList = useTrackList(trackListOptions);

  // Gestion de la sélection
  const handleTrackSelect = (trackId: number, selected: boolean) => {
    setSelectedTracks((prev) =>
      selected ? [...prev, trackId] : prev.filter((id) => id !== trackId)
    );
  };

  const handleSelectAll = (selected: boolean) => {
    if (selected) {
      setSelectedTracks(trackList.filteredTracks.map((track) => track.id));
    } else {
      setSelectedTracks([]);
    }
  };

  const handleClearSelection = () => {
    setSelectedTracks([]);
  };

  // Déterminer si des filtres sont actifs
  const hasActiveFilters = useMemo(() => {
    return Boolean(
      trackList.filterOptions.genre ||
        trackList.filterOptions.artist ||
        trackList.filterOptions.album ||
        trackList.filterOptions.year ||
        trackList.filterOptions.minDuration ||
        trackList.filterOptions.maxDuration
    );
  }, [trackList.filterOptions]);

  // Déterminer si une recherche est active
  // Note: searchQuery n'est pas exposé dans le return de useTrackList
  // On utilise un état local pour suivre la recherche
  const [searchQuery, setSearchQueryState] = useState('');
  const hasActiveSearch = useMemo(() => {
    return Boolean(searchQuery && searchQuery.trim().length > 0);
  }, [searchQuery]);
  
  // Synchroniser searchQuery avec le hook si nécessaire
  // Pour l'instant, on utilise un état local car searchQuery n'est pas dans le return

  // Déterminer le type d'état vide
  const emptyStateType = trackList.error
    ? 'error'
    : hasActiveFilters || hasActiveSearch
    ? 'no-results'
    : 'no-tracks';

  return (
    <div className={cn('space-y-4', className)}>
      {/* Barre d'outils : Filtres, Tri, Toggle vue */}
      <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
        <div className="flex flex-col sm:flex-row gap-4 flex-1 w-full">
          {/* Filtres */}
          {showFilters && (
            <div className="flex-1">
              <TrackFilters
                filters={trackList.filterOptions}
                onFiltersChange={trackList.setFilterOptions}
                searchQuery={searchQuery}
                onSearchChange={(query) => {
                  setSearchQueryState(query);
                  trackList.setSearchQuery(query);
                }}
                availableGenres={availableGenres}
                availableArtists={availableArtists}
                availableYears={availableYears}
                collapsible={true}
              />
            </div>
          )}

          {/* Tri */}
          {showSort && (
            <TrackSort
              sortOptions={trackList.sortOptions}
              onSortChange={(options) => {
                trackList.setSortField(options.field);
                trackList.setSortOrder(options.order);
              }}
              persistPreference={persistSort}
              storageKey={`${storageKeyPrefix}_sort`}
            />
          )}
        </div>

        {/* Toggle vue */}
        {showViewToggle && (
          <ViewToggle
            value={trackList.displayMode}
            onChange={trackList.setDisplayMode}
            persistPreference={true}
            storageKey={`${storageKeyPrefix}_viewMode`}
          />
        )}
      </div>

      {/* Liste ou Grille de pistes */}
      {trackList.displayMode === 'list' ? (
        <TrackList
          tracks={trackList.filteredTracks}
          onTrackClick={onTrackClick}
          onTrackPlay={onTrackPlay}
          onTrackLike={onTrackLike}
          onTrackMore={onTrackMore}
          isLiked={isLiked}
          isPlaying={isPlaying}
          currentPlayingId={currentPlayingId}
          isLoading={trackList.isLoading}
          showSelection={showSelection}
          selectedTracks={selectedTracks}
          onTrackSelect={handleTrackSelect}
          onSelectAll={handleSelectAll}
          onSelectedPlay={onSelectedPlay}
          onSelectedDelete={onSelectedDelete}
          onSelectedLike={onSelectedLike}
          onSelectedDownload={onSelectedDownload}
          onSelectedMore={onSelectedMore}
          onClearSelection={handleClearSelection}
          emptyMessage={
            emptyStateType === 'error'
              ? 'Erreur lors du chargement'
              : emptyStateType === 'no-results'
              ? 'Aucun résultat trouvé'
              : undefined
          }
          emptyDescription={
            emptyStateType === 'error'
              ? 'Une erreur est survenue lors du chargement des pistes.'
              : undefined
          }
          emptyIcon={emptyStateType === 'error' ? 'error' : emptyStateType === 'no-results' ? 'search' : 'music'}
          hasFilters={hasActiveFilters}
          hasSearch={hasActiveSearch}
        />
      ) : (
        <TrackGrid
          tracks={trackList.filteredTracks}
          onTrackClick={onTrackClick}
          onTrackPlay={onTrackPlay}
          onTrackLike={onTrackLike}
          onTrackMore={onTrackMore}
          isLiked={isLiked}
          isPlaying={isPlaying}
          currentPlayingId={currentPlayingId}
          isLoading={trackList.isLoading}
          columns={gridColumns}
          showDensitySelector={showDensitySelector}
          persistDensity={true}
          densityStorageKey={`${storageKeyPrefix}_gridDensity`}
          emptyMessage={
            emptyStateType === 'error'
              ? 'Erreur lors du chargement'
              : emptyStateType === 'no-results'
              ? 'Aucun résultat trouvé'
              : undefined
          }
          emptyDescription={
            emptyStateType === 'error'
              ? 'Une erreur est survenue lors du chargement des pistes.'
              : undefined
          }
          emptyIcon={emptyStateType === 'error' ? 'error' : emptyStateType === 'no-results' ? 'search' : 'music'}
        />
      )}

      {/* État vide avec gestion d'erreur (si TrackList/TrackGrid n'affiche pas l'erreur) */}
      {trackList.error && trackList.filteredTracks.length === 0 && !trackList.isLoading && (
        <TrackListEmpty
          type="error"
          onRetry={trackList.refreshTracks}
          hasFilters={hasActiveFilters}
          hasSearch={hasActiveSearch}
        />
      )}

      {/* Pagination */}
      {showPagination && trackList.totalPages > 1 && (
        <TrackListPagination
          currentPage={trackList.pagination.page}
          totalPages={trackList.totalPages}
          totalItems={trackList.total}
          itemsPerPage={trackList.pagination.limit}
          onPageChange={trackList.setPage}
        />
      )}
    </div>
  );
}

export default TrackListContainer;

