/**
 * Composant PlaylistList
 * T0459: Create Playlist List Component
 */

import { useState } from 'react';
import { usePlaylists } from '../hooks/usePlaylist';
import { PlaylistCard } from './PlaylistCard';
import { PlaylistListSkeleton } from './PlaylistListSkeleton';
import { PlaylistBatchActions } from './PlaylistBatchActions';
import { Button } from '@/components/ui/button';
import { List, Grid, ChevronLeft, ChevronRight, CheckSquare, Square } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { Playlist } from '../types';

interface PlaylistListProps {
  view?: 'grid' | 'list';
  limit?: number;
  className?: string;
  enableSelection?: boolean;
}

export function PlaylistList({ 
  view: initialView = 'grid', 
  limit = 20, 
  className,
  enableSelection = false,
}: PlaylistListProps) {
  const [currentView, setCurrentView] = useState<'grid' | 'list'>(initialView);
  const [offset, setOffset] = useState(0);
  const [selectedPlaylists, setSelectedPlaylists] = useState<Set<number>>(new Set());
  
  const { data, isLoading, error } = usePlaylists(limit, offset);
  
  const handlePreviousPage = () => {
    if (offset >= limit) {
      setOffset(offset - limit);
    }
  };
  
  const handleNextPage = () => {
    if (data && offset + limit < data.total) {
      setOffset(offset + limit);
    }
  };
  
  const totalPages = data ? Math.ceil(data.total / limit) : 0;
  const currentPage = data ? Math.floor(offset / limit) + 1 : 1;

  // Gestion de la sélection
  const handlePlaylistSelect = (playlist: Playlist, selected: boolean) => {
    setSelectedPlaylists((prev) => {
      const newSet = new Set(prev);
      if (selected) {
        newSet.add(playlist.id);
      } else {
        newSet.delete(playlist.id);
      }
      return newSet;
    });
  };

  const handleSelectAll = () => {
    if (!data) return;
    const allSelected = data.playlists.every((p) => selectedPlaylists.has(p.id));
    if (allSelected) {
      setSelectedPlaylists(new Set());
    } else {
      setSelectedPlaylists(new Set(data.playlists.map((p) => p.id)));
    }
  };

  const handleClearSelection = () => {
    setSelectedPlaylists(new Set());
  };

  const selectedPlaylistsArray = data?.playlists.filter((p) => selectedPlaylists.has(p.id)) || [];
  const isAllSelected = data && data.playlists.length > 0 && data.playlists.every((p) => selectedPlaylists.has(p.id));
  
  if (isLoading && !data) {
    return (
      <div className={cn('space-y-4', className)} role="region" aria-live="polite">
        <PlaylistListSkeleton count={limit} view={currentView} />
      </div>
    );
  }
  
  if (error) {
    return (
      <div className={cn('text-center py-12', className)} role="alert">
        <p className="text-destructive">Erreur lors du chargement des playlists</p>
        {error instanceof Error && (
          <p className="text-sm text-muted-foreground mt-2">{error.message}</p>
        )}
      </div>
    );
  }
  
  if (!data?.playlists.length) {
    return (
      <div className={cn('text-center py-12', className)} role="region" aria-live="polite">
        <p className="text-muted-foreground">Aucune playlist trouvée</p>
      </div>
    );
  }
  
  return (
    <div className={cn('space-y-4', className)} role="region" aria-label="Liste des playlists">
      {/* Batch Actions */}
      {enableSelection && selectedPlaylists.size > 0 && (
        <PlaylistBatchActions
          selectedPlaylists={selectedPlaylistsArray}
          onSelectionClear={handleClearSelection}
        />
      )}

      {/* Toolbar: Selection toggle and View toggle */}
      <div className="flex justify-between items-center gap-2">
        {/* Select All - Only shown when selection is enabled */}
        {enableSelection && data && data.playlists.length > 0 && (
          <Button
            variant="outline"
            size="sm"
            onClick={handleSelectAll}
            className="touch-manipulation min-h-[44px] sm:min-h-0"
            aria-label={isAllSelected ? 'Désélectionner toutes' : 'Sélectionner toutes'}
          >
            {isAllSelected ? (
              <CheckSquare className="h-4 w-4 sm:mr-2" aria-hidden="true" />
            ) : (
              <Square className="h-4 w-4 sm:mr-2" aria-hidden="true" />
            )}
            <span className="hidden sm:inline">
              {isAllSelected ? 'Tout désélectionner' : 'Tout sélectionner'}
            </span>
          </Button>
        )}
        
        {/* View Toggle - Hidden on mobile, shown on tablet+ */}
        <div className="hidden sm:flex justify-end items-center gap-2 ml-auto">
        <div 
          className="inline-flex items-center gap-1 p-1 rounded-lg bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700"
          role="group"
          aria-label="Changer l'affichage des playlists"
        >
          <button
            type="button"
            onClick={() => setCurrentView('list')}
            className={cn(
              'flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-all duration-200',
              'hover:bg-gray-200 dark:hover:bg-gray-700',
              'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
              'touch-manipulation', // Optimize touch response
              currentView === 'list'
                ? 'bg-white dark:bg-gray-700 text-blue-600 dark:text-blue-400 shadow-sm'
                : 'text-gray-600 dark:text-gray-400'
            )}
            aria-label="Affichage en liste"
            aria-pressed={currentView === 'list'}
          >
            <List className="h-4 w-4" aria-hidden="true" />
            <span className="hidden md:inline">Liste</span>
          </button>
          <button
            type="button"
            onClick={() => setCurrentView('grid')}
            className={cn(
              'flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-all duration-200',
              'hover:bg-gray-200 dark:hover:bg-gray-700',
              'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
              'touch-manipulation', // Optimize touch response
              currentView === 'grid'
                ? 'bg-white dark:bg-gray-700 text-blue-600 dark:text-blue-400 shadow-sm'
                : 'text-gray-600 dark:text-gray-400'
            )}
            aria-label="Affichage en grille"
            aria-pressed={currentView === 'grid'}
          >
            <Grid className="h-4 w-4" aria-hidden="true" />
            <span className="hidden md:inline">Grille</span>
          </button>
        </div>
      </div>
      </div>
      
      {/* Playlist List/Grid - Mobile optimized */}
      <div
        className={cn(
          currentView === 'grid'
            ? 'grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-4'
            : 'flex flex-col gap-2 sm:gap-3'
        )}
        role="list"
        aria-label="Playlists disponibles"
      >
        {data.playlists.map((playlist: Playlist) => (
          <PlaylistCard
            key={playlist.id}
            playlist={playlist}
            className={currentView === 'list' ? 'flex-row' : ''}
            selectable={enableSelection}
            selected={selectedPlaylists.has(playlist.id)}
            onSelect={handlePlaylistSelect}
          />
        ))}
        {/* Show skeleton while loading more */}
        {isLoading && (
          <PlaylistListSkeleton count={4} view={currentView} />
        )}
      </div>
      
      {/* Pagination - Mobile optimized */}
      {totalPages > 1 && (
        <div 
          className="flex flex-col sm:flex-row items-center justify-between pt-4 border-t gap-3 sm:gap-0"
          role="navigation"
          aria-label="Pagination des playlists"
        >
          <div className="text-xs sm:text-sm text-muted-foreground text-center sm:text-left" aria-live="polite">
            Page {currentPage} sur {totalPages} ({data.total} playlists)
          </div>
          <div className="flex items-center gap-2 w-full sm:w-auto">
            <Button
              variant="outline"
              size="sm"
              onClick={handlePreviousPage}
              disabled={offset === 0 || isLoading}
              aria-label="Page précédente"
              className="flex-1 sm:flex-initial touch-manipulation min-h-[44px] sm:min-h-0"
            >
              <ChevronLeft className="h-4 w-4 sm:mr-1" aria-hidden="true" />
              <span className="hidden sm:inline">Précédent</span>
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={handleNextPage}
              disabled={!data || offset + limit >= data.total || isLoading}
              aria-label="Page suivante"
              className="flex-1 sm:flex-initial touch-manipulation min-h-[44px] sm:min-h-0"
            >
              <span className="hidden sm:inline">Suivant</span>
              <ChevronRight className="h-4 w-4 sm:ml-1" aria-hidden="true" />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}