/**
 * Composant TrackSort
 * Options de tri pour la liste de pistes : titre, artiste, date, durée, popularité
 */

import { useState, useEffect, useCallback } from 'react';
import {
  ArrowUpDown,
  ArrowUp,
  ArrowDown,
  Music,
  User,
  Calendar,
  Clock,
  TrendingUp,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { logger } from '@/utils/logger';
import type { TrackSortOptions, TrackSortOption } from '../types';

export interface TrackSortProps {
  sortOptions: TrackSortOptions;
  onSortChange: (options: TrackSortOptions) => void;
  persistPreference?: boolean;
  storageKey?: string;
  className?: string;
  showOrderToggle?: boolean;
  availableFields?: TrackSortOption[];
}

const SORT_FIELD_LABELS: Record<TrackSortOption, string> = {
  title: 'Titre',
  artist: 'Artiste',
  album: 'Album',
  duration: 'Durée',
  date: 'Date',
  popularity: 'Popularité',
};

const SORT_FIELD_ICONS: Record<TrackSortOption, React.ElementType> = {
  title: Music,
  artist: User,
  album: Music,
  duration: Clock,
  date: Calendar,
  popularity: TrendingUp,
};

export function TrackSort({
  sortOptions,
  onSortChange,
  persistPreference = false,
  storageKey = 'trackSortOptions',
  className,
  showOrderToggle = true,
  availableFields = [
    'title',
    'artist',
    'album',
    'duration',
    'date',
    'popularity',
  ],
}: TrackSortProps) {
  const [localSortOptions, setLocalSortOptions] =
    useState<TrackSortOptions>(sortOptions);

  // Charger la préférence depuis localStorage au montage si persistPreference est activé
  useEffect(() => {
    if (persistPreference && typeof window !== 'undefined') {
      const stored = localStorage.getItem(storageKey);
      if (stored) {
        try {
          const parsed = JSON.parse(stored) as TrackSortOptions;
          if (parsed.field && parsed.order) {
            setLocalSortOptions(parsed);
            onSortChange(parsed);
          }
        } catch (error) {
          logger.error('Error parsing stored sort options:', { error });
        }
      }
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // Mettre à jour les options locales quand les props changent
  useEffect(() => {
    setLocalSortOptions(sortOptions);
  }, [sortOptions]);

  // Persister la préférence dans localStorage
  useEffect(() => {
    if (persistPreference && typeof window !== 'undefined') {
      localStorage.setItem(storageKey, JSON.stringify(localSortOptions));
    }
  }, [localSortOptions, persistPreference, storageKey]);

  const handleFieldChange = useCallback(
    (field: TrackSortOption) => {
      const newOptions: TrackSortOptions = {
        ...localSortOptions,
        field,
      };
      setLocalSortOptions(newOptions);
      onSortChange(newOptions);
    },
    [localSortOptions, onSortChange],
  );

  const handleOrderToggle = useCallback(() => {
    const newOptions: TrackSortOptions = {
      ...localSortOptions,
      order: localSortOptions.order === 'asc' ? 'desc' : 'asc',
    };
    setLocalSortOptions(newOptions);
    onSortChange(newOptions);
  }, [localSortOptions, onSortChange]);

  const FieldIcon = SORT_FIELD_ICONS[localSortOptions.field] || Music;

  return (
    <div
      className={cn('flex items-center gap-2', className)}
      role="group"
      aria-label="Options de tri"
    >
      {/* Sélecteur de champ */}
      <div className="relative">
        <label htmlFor="track-sort-field" className="sr-only">
          Champ de tri
        </label>
        <div className="relative">
          <FieldIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
          <select
            id="track-sort-field"
            value={localSortOptions.field}
            onChange={(e) =>
              handleFieldChange(e.target.value as TrackSortOption)
            }
            className={cn(
              'pl-10 pr-8 py-2 border border-gray-300 dark:border-gray-600',
              'rounded-md bg-white dark:bg-gray-700',
              'text-sm font-medium text-gray-900 dark:text-white',
              'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent',
              'appearance-none cursor-pointer',
            )}
            aria-label="Sélectionner le champ de tri"
          >
            {availableFields.map((field) => (
              <option key={field} value={field}>
                {SORT_FIELD_LABELS[field]}
              </option>
            ))}
          </select>
          <ArrowUpDown className="absolute right-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
        </div>
      </div>

      {/* Toggle ordre asc/desc */}
      {showOrderToggle && (
        <button
          type="button"
          onClick={handleOrderToggle}
          className={cn(
            'p-2 rounded-md border border-gray-300 dark:border-gray-600',
            'bg-white dark:bg-gray-700',
            'text-gray-700 dark:text-gray-300',
            'hover:bg-gray-50 dark:hover:bg-gray-600',
            'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
            'transition-colors',
            'flex items-center justify-center',
          )}
          aria-label={`Trier par ordre ${localSortOptions.order === 'asc' ? 'décroissant' : 'croissant'}`}
          aria-pressed={localSortOptions.order === 'desc'}
        >
          {localSortOptions.order === 'asc' ? (
            <ArrowUp className="h-4 w-4" aria-hidden="true" />
          ) : (
            <ArrowDown className="h-4 w-4" aria-hidden="true" />
          )}
          <span className="sr-only">
            {localSortOptions.order === 'asc'
              ? 'Ordre croissant'
              : 'Ordre décroissant'}
          </span>
        </button>
      )}
    </div>
  );
}

export default TrackSort;
