/**
 * Composant TrackFilters
 * Filtres pour la liste de pistes : genre, artiste, date, durée, recherche
 */

import React, { useState, useCallback } from 'react';
import { Search, X, Filter, Music, User, Calendar, Clock } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { TrackFilterOptions } from '../types';

export interface TrackFiltersProps {
  filters: TrackFilterOptions;
  onFiltersChange: (filters: TrackFilterOptions) => void;
  searchQuery?: string;
  onSearchChange?: (query: string) => void;
  availableGenres?: string[];
  availableArtists?: string[];
  availableYears?: number[];
  className?: string;
  showSearch?: boolean;
  showGenre?: boolean;
  showArtist?: boolean;
  showYear?: boolean;
  showDuration?: boolean;
  collapsible?: boolean;
}

export function TrackFilters({
  filters,
  onFiltersChange,
  searchQuery = '',
  onSearchChange,
  availableGenres = [],
  availableArtists = [],
  availableYears = [],
  className,
  showSearch = true,
  showGenre = true,
  showArtist = true,
  showYear = true,
  showDuration = true,
  collapsible = false,
}: TrackFiltersProps) {
  const [isExpanded, setIsExpanded] = useState(!collapsible);
  const [localFilters, setLocalFilters] = useState<TrackFilterOptions>(filters);
  const [localSearchQuery, setLocalSearchQuery] = useState(searchQuery);

  // Mettre à jour les filtres locaux quand les props changent
  React.useEffect(() => {
    setLocalFilters(filters);
  }, [filters]);

  // Mettre à jour la recherche locale quand la prop change
  React.useEffect(() => {
    setLocalSearchQuery(searchQuery);
  }, [searchQuery]);

  const handleFilterChange = useCallback(
    (key: keyof TrackFilterOptions, value: string | number | undefined) => {
      const newFilters = {
        ...localFilters,
        [key]: value === '' || value === undefined ? undefined : value,
      };
      setLocalFilters(newFilters);
      onFiltersChange(newFilters);
    },
    [localFilters, onFiltersChange],
  );

  const handleSearchChange = useCallback(
    (value: string) => {
      setLocalSearchQuery(value);
      onSearchChange?.(value);
    },
    [onSearchChange],
  );

  const handleClearFilters = useCallback(() => {
    const clearedFilters: TrackFilterOptions = {};
    setLocalFilters(clearedFilters);
    onFiltersChange(clearedFilters);
    if (onSearchChange) {
      setLocalSearchQuery('');
      onSearchChange('');
    }
  }, [onFiltersChange, onSearchChange]);

  const hasActiveFilters = Boolean(
    localSearchQuery ||
      localFilters.genre ||
      localFilters.artist ||
      localFilters.album ||
      localFilters.year ||
      localFilters.minDuration ||
      localFilters.maxDuration,
  );

  return (
    <div
      className={cn(
        'bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4',
        className,
      )}
    >
      {/* Header avec toggle si collapsible */}
      {collapsible && (
        <button
          type="button"
          onClick={() => setIsExpanded(!isExpanded)}
          className="flex items-center justify-between w-full mb-4 text-left"
          aria-expanded={isExpanded}
          aria-controls="track-filters-content"
        >
          <div className="flex items-center gap-2">
            <Filter className="h-5 w-5 text-gray-600 dark:text-gray-400" />
            <span className="font-medium text-gray-900 dark:text-white">
              Filtres
            </span>
            {hasActiveFilters && (
              <span className="px-2 py-0.5 text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400 rounded-full">
                Actifs
              </span>
            )}
          </div>
          <span className="text-sm text-gray-500 dark:text-gray-400">
            {isExpanded ? 'Masquer' : 'Afficher'}
          </span>
        </button>
      )}

      {/* Contenu des filtres */}
      <div
        id="track-filters-content"
        className={cn('space-y-4', collapsible && !isExpanded && 'hidden')}
      >
        {/* Recherche */}
        {showSearch && (
          <div className="relative">
            <label
              htmlFor="track-search"
              className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
            >
              Recherche
            </label>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
              <input
                id="track-search"
                type="text"
                placeholder="Rechercher par titre, artiste, album..."
                value={localSearchQuery}
                onChange={(e) => handleSearchChange(e.target.value)}
                className={cn(
                  'w-full pl-10 pr-10 py-2 border border-gray-300 dark:border-gray-600',
                  'rounded-md bg-white dark:bg-gray-700',
                  'text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500',
                  'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent',
                )}
                aria-label="Rechercher des pistes"
              />
              {localSearchQuery && (
                <button
                  type="button"
                  onClick={() => handleSearchChange('')}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                  aria-label="Effacer la recherche"
                >
                  <X className="h-4 w-4" />
                </button>
              )}
            </div>
          </div>
        )}

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {/* Filtre Genre */}
          {showGenre && (
            <div>
              <label
                htmlFor="track-genre"
                className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >
                <Music className="inline h-4 w-4 mr-1" />
                Genre
              </label>
              <select
                id="track-genre"
                value={localFilters.genre || ''}
                onChange={(e) => handleFilterChange('genre', e.target.value)}
                className={cn(
                  'w-full px-3 py-2 border border-gray-300 dark:border-gray-600',
                  'rounded-md bg-white dark:bg-gray-700',
                  'text-gray-900 dark:text-white',
                  'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent',
                )}
                aria-label="Filtrer par genre"
              >
                <option value="">Tous les genres</option>
                {availableGenres.map((genre) => (
                  <option key={genre} value={genre}>
                    {genre}
                  </option>
                ))}
              </select>
            </div>
          )}

          {/* Filtre Artiste */}
          {showArtist && (
            <div>
              <label
                htmlFor="track-artist"
                className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >
                <User className="inline h-4 w-4 mr-1" />
                Artiste
              </label>
              {availableArtists.length > 0 ? (
                <select
                  id="track-artist"
                  value={localFilters.artist || ''}
                  onChange={(e) => handleFilterChange('artist', e.target.value)}
                  className={cn(
                    'w-full px-3 py-2 border border-gray-300 dark:border-gray-600',
                    'rounded-md bg-white dark:bg-gray-700',
                    'text-gray-900 dark:text-white',
                    'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent',
                  )}
                  aria-label="Filtrer par artiste"
                >
                  <option value="">Tous les artistes</option>
                  {availableArtists.map((artist) => (
                    <option key={artist} value={artist}>
                      {artist}
                    </option>
                  ))}
                </select>
              ) : (
                <input
                  id="track-artist"
                  type="text"
                  placeholder="Nom de l'artiste"
                  value={localFilters.artist || ''}
                  onChange={(e) => handleFilterChange('artist', e.target.value)}
                  className={cn(
                    'w-full px-3 py-2 border border-gray-300 dark:border-gray-600',
                    'rounded-md bg-white dark:bg-gray-700',
                    'text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500',
                    'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent',
                  )}
                  aria-label="Filtrer par artiste"
                />
              )}
            </div>
          )}

          {/* Filtre Année */}
          {showYear && (
            <div>
              <label
                htmlFor="track-year"
                className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >
                <Calendar className="inline h-4 w-4 mr-1" />
                Année
              </label>
              {availableYears.length > 0 ? (
                <select
                  id="track-year"
                  value={localFilters.year || ''}
                  onChange={(e) =>
                    handleFilterChange(
                      'year',
                      e.target.value ? Number(e.target.value) : undefined,
                    )
                  }
                  className={cn(
                    'w-full px-3 py-2 border border-gray-300 dark:border-gray-600',
                    'rounded-md bg-white dark:bg-gray-700',
                    'text-gray-900 dark:text-white',
                    'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent',
                  )}
                  aria-label="Filtrer par année"
                >
                  <option value="">Toutes les années</option>
                  {availableYears.map((year) => (
                    <option key={year} value={year}>
                      {year}
                    </option>
                  ))}
                </select>
              ) : (
                <input
                  id="track-year"
                  type="number"
                  placeholder="Année"
                  value={localFilters.year || ''}
                  onChange={(e) =>
                    handleFilterChange(
                      'year',
                      e.target.value ? Number(e.target.value) : undefined,
                    )
                  }
                  min="1900"
                  max={new Date().getFullYear()}
                  className={cn(
                    'w-full px-3 py-2 border border-gray-300 dark:border-gray-600',
                    'rounded-md bg-white dark:bg-gray-700',
                    'text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500',
                    'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent',
                  )}
                  aria-label="Filtrer par année"
                />
              )}
            </div>
          )}

          {/* Filtre Durée */}
          {showDuration && (
            <div>
              <label
                htmlFor="track-duration"
                className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >
                <Clock className="inline h-4 w-4 mr-1" />
                Durée (min)
              </label>
              <div className="flex gap-2">
                <input
                  id="track-duration-min"
                  type="number"
                  placeholder="Min"
                  value={localFilters.minDuration || ''}
                  onChange={(e) =>
                    handleFilterChange(
                      'minDuration',
                      e.target.value ? Number(e.target.value) : undefined,
                    )
                  }
                  min="0"
                  step="0.1"
                  className={cn(
                    'w-full px-3 py-2 border border-gray-300 dark:border-gray-600',
                    'rounded-md bg-white dark:bg-gray-700',
                    'text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500',
                    'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent',
                  )}
                  aria-label="Durée minimale en minutes"
                />
                <input
                  id="track-duration-max"
                  type="number"
                  placeholder="Max"
                  value={localFilters.maxDuration || ''}
                  onChange={(e) =>
                    handleFilterChange(
                      'maxDuration',
                      e.target.value ? Number(e.target.value) : undefined,
                    )
                  }
                  min="0"
                  step="0.1"
                  className={cn(
                    'w-full px-3 py-2 border border-gray-300 dark:border-gray-600',
                    'rounded-md bg-white dark:bg-gray-700',
                    'text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500',
                    'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent',
                  )}
                  aria-label="Durée maximale en minutes"
                />
              </div>
            </div>
          )}
        </div>

        {/* Bouton Effacer les filtres */}
        {hasActiveFilters && (
          <div className="flex justify-end pt-2 border-t border-gray-200 dark:border-gray-700">
            <button
              type="button"
              onClick={handleClearFilters}
              className={cn(
                'flex items-center gap-2 px-4 py-2 text-sm font-medium',
                'text-gray-700 dark:text-gray-300',
                'hover:bg-gray-100 dark:hover:bg-gray-700',
                'rounded-md transition-colors',
                'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
              )}
              aria-label="Effacer tous les filtres"
            >
              <X className="h-4 w-4" />
              Effacer les filtres
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

export default TrackFilters;
