/**
 * 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-4 py-2 text-sm font-medium rounded-lg',
          'bg-card border border-border',
          'text-foreground',
          'hover:bg-muted',
          '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-card border border-border 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-muted',
                'focus:outline-none focus:bg-muted',
                'transition-colors',
                currentQuality === quality.value &&
                  'bg-primary/10',
              )}
              role="option"
              aria-selected={currentQuality === quality.value}
            >
              <div className="flex flex-col">
                <span className="font-medium text-foreground">
                  {quality.label}
                </span>
                {quality.description && (
                  <span className="text-xs text-muted-foreground">
                    {quality.description}
                  </span>
                )}
              </div>
              {currentQuality === quality.value && (
                <Check
                  className="h-4 w-4 text-muted-foreground"
                  aria-hidden="true"
                />
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

export default QualitySelector;
