/**
 * Composant QualitySelector
 * Sélecteur de qualité audio avec dropdown
 */

import { useState, useRef, useEffect } from 'react';
import { ChevronDown, Check } from 'lucide-react';
import { cn } from '@/lib/utils';

export type AudioQuality = 'auto' | 'low' | 'medium' | 'high' | 'lossless';

export interface QualityOption {
  value: AudioQuality;
  label: string;
  description?: string;
}

export interface QualitySelectorProps {
  currentQuality: AudioQuality;
  availableQualities?: AudioQuality[];
  onQualityChange: (quality: AudioQuality) => void;
  className?: string;
  disabled?: boolean;
}

const DEFAULT_QUALITIES: QualityOption[] = [
  { value: 'auto', label: 'Auto', description: 'Qualité automatique' },
  { value: 'low', label: 'Faible', description: '128 kbps' },
  { value: 'medium', label: 'Moyenne', description: '192 kbps' },
  { value: 'high', label: 'Haute', description: '320 kbps' },
  { value: 'lossless', label: 'Sans perte', description: 'FLAC / WAV' },
];

export function QualitySelector({
  currentQuality,
  availableQualities,
  onQualityChange,
  className,
  disabled = false,
}: QualitySelectorProps) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Filtrer les qualités disponibles
  const qualities = availableQualities
    ? DEFAULT_QUALITIES.filter((q) => availableQualities.includes(q.value))
    : DEFAULT_QUALITIES;

  const currentQualityOption =
    qualities.find((q) => q.value === currentQuality) || qualities[0];

  // Fermer le dropdown quand on clique en dehors
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }
    return undefined;
  }, [isOpen]);

  const handleSelect = (quality: AudioQuality) => {
    onQualityChange(quality);
    setIsOpen(false);
  };

  return (
    <div ref={dropdownRef} className={cn('relative', className)}>
      {/* Button */}
      <button
        type="button"
        onClick={() => !disabled && setIsOpen(!isOpen)}
        disabled={disabled}
        className={cn(
          'flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-lg',
          'bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600',
          'text-gray-700 dark:text-gray-300',
          'hover:bg-gray-50 dark:hover:bg-gray-700',
          'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
          'disabled:opacity-50 disabled:cursor-not-allowed',
          'transition-colors',
        )}
        aria-label={`Qualité audio: ${currentQualityOption.label}`}
        aria-expanded={isOpen}
        aria-haspopup="listbox"
        aria-disabled={disabled}
      >
        <span>{currentQualityOption.label}</span>
        <ChevronDown
          className={cn(
            'h-4 w-4 transition-transform',
            isOpen && 'transform rotate-180',
          )}
          aria-hidden="true"
        />
      </button>

      {/* Dropdown */}
      {isOpen && !disabled && (
        <div
          className="absolute z-50 mt-1 w-48 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg shadow-lg"
          role="listbox"
        >
          {qualities.map((quality) => (
            <button
              key={quality.value}
              type="button"
              onClick={() => handleSelect(quality.value)}
              className={cn(
                'w-full flex items-center justify-between px-4 py-2 text-sm text-left',
                'hover:bg-gray-100 dark:hover:bg-gray-700',
                'focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-700',
                'transition-colors',
                currentQuality === quality.value &&
                  'bg-blue-50 dark:bg-blue-900/20',
              )}
              role="option"
              aria-selected={currentQuality === quality.value}
            >
              <div className="flex flex-col">
                <span className="font-medium text-gray-900 dark:text-white">
                  {quality.label}
                </span>
                {quality.description && (
                  <span className="text-xs text-gray-500 dark:text-gray-400">
                    {quality.description}
                  </span>
                )}
              </div>
              {currentQuality === quality.value && (
                <Check
                  className="h-4 w-4 text-blue-600 dark:text-blue-400"
                  aria-hidden="true"
                />
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

export default QualitySelector;
