/**
 * Composant PlaybackSpeedControl
 * Contrôle de la vitesse de lecture avec dropdown
 */

import { useState, useRef, useEffect } from 'react';
import { ChevronDown, Check } from 'lucide-react';

import { cn } from '@/lib/utils';

export type PlaybackSpeed = 0.5 | 0.75 | 1 | 1.25 | 1.5 | 1.75 | 2;

export interface PlaybackSpeedOption {
  value: PlaybackSpeed;
  label: string;
}

export interface PlaybackSpeedControlProps {
  currentSpeed: PlaybackSpeed;
  onSpeedChange: (speed: PlaybackSpeed) => void;
  className?: string;
  disabled?: boolean;
  availableSpeeds?: PlaybackSpeed[];
}

const DEFAULT_SPEEDS: PlaybackSpeedOption[] = [
  { value: 0.5, label: '0.5x' },
  { value: 0.75, label: '0.75x' },
  { value: 1, label: '1x' },
  { value: 1.25, label: '1.25x' },
  { value: 1.5, label: '1.5x' },
  { value: 1.75, label: '1.75x' },
  { value: 2, label: '2x' },
];

export function PlaybackSpeedControl({
  currentSpeed,
  onSpeedChange,
  className,
  disabled = false,
  availableSpeeds,
}: PlaybackSpeedControlProps) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Filtrer les vitesses disponibles
  const speeds = availableSpeeds
    ? DEFAULT_SPEEDS.filter((s) => availableSpeeds.includes(s.value))
    : DEFAULT_SPEEDS;

  const currentSpeedOption =
    speeds.find((s) => s.value === currentSpeed) ||
    speeds.find((s) => s.value === 1) ||
    speeds[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 = (speed: PlaybackSpeed) => {
    onSpeedChange(speed);
    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={`Vitesse de lecture: ${currentSpeedOption.label}`}
        aria-expanded={isOpen}
        aria-haspopup="listbox"
        aria-disabled={disabled}
        title={`Vitesse: ${currentSpeedOption.label}`}
      >
        <span>{currentSpeedOption.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-32 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg shadow-lg"
          role="listbox"
        >
          {speeds.map((speed) => (
            <button
              key={speed.value}
              type="button"
              onClick={() => handleSelect(speed.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',
                currentSpeed === speed.value &&
                  'bg-blue-50 dark:bg-blue-900/20',
              )}
              role="option"
              aria-selected={currentSpeed === speed.value}
            >
              <span className="font-medium text-gray-900 dark:text-white">
                {speed.label}
              </span>
              {currentSpeed === speed.value && (
                <Check
                  className="h-4 w-4 text-blue-600 dark:text-blue-400"
                  aria-hidden="true"
                />
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

export default PlaybackSpeedControl;
