import { useRef } from 'react';
import type { KeyboardEvent, ReactNode } from 'react';
import { cn } from '@/lib/utils';

export interface SegmentedOption<T extends string> {
  value: T;
  label: ReactNode;
  title?: string;
}

export interface SegmentedControlProps<T extends string> {
  /** Names the group for assistive tech. Required — a bare radiogroup is noise. */
  label: string;
  options: SegmentedOption<T>[];
  value: T;
  onChange: (value: T) => void;
  className?: string;
  optionClassName?: string;
}

/**
 * The one-of-N control the shell uses for speed and for the run switcher.
 *
 * It exists because a row of buttons with `aria-checked` is not a radiogroup:
 * the pattern also requires a ROVING tabindex, so Tab moves past the whole
 * control rather than through every option, and the arrow keys move within it.
 * Getting that wrong is the most common a11y bug in a segmented control, which
 * is why there is one implementation here instead of three inline copies.
 */
export function SegmentedControl<T extends string>({
  label,
  options,
  value,
  onChange,
  className,
  optionClassName,
}: SegmentedControlProps<T>) {
  const refs = useRef<(HTMLButtonElement | null)[]>([]);
  const index = Math.max(
    options.findIndex((option) => option.value === value),
    0,
  );

  const move = (to: number, event: KeyboardEvent) => {
    if (options.length === 0) return;
    event.preventDefault();
    // Wraps: a radiogroup's arrows cycle rather than dead-ending.
    const next = (to + options.length) % options.length;
    const option = options[next];
    if (!option) return;
    onChange(option.value);
    refs.current[next]?.focus();
  };

  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    switch (event.key) {
      case 'ArrowRight':
      case 'ArrowDown':
        move(index + 1, event);
        break;
      case 'ArrowLeft':
      case 'ArrowUp':
        move(index - 1, event);
        break;
      case 'Home':
        move(0, event);
        break;
      case 'End':
        move(options.length - 1, event);
        break;
      default:
        break;
    }
  };

  return (
    <div
      role="radiogroup"
      aria-label={label}
      onKeyDown={onKeyDown}
      className={cn('flex flex-wrap items-center gap-0.5 rounded-lg bg-surface-2 p-0.5', className)}
    >
      {options.map((option, position) => {
        const selected = option.value === value;
        return (
          <button
            key={option.value}
            type="button"
            role="radio"
            aria-checked={selected}
            tabIndex={position === index ? 0 : -1}
            {...(option.title ? { title: option.title } : {})}
            ref={(node) => {
              refs.current[position] = node;
            }}
            onClick={() => onChange(option.value)}
            className={cn(
              'min-h-9 rounded-md px-2.5 text-xs font-medium transition-colors duration-2 ease-enter',
              selected ? 'bg-surface text-fg shadow-sm' : 'text-muted hover:text-fg',
              optionClassName,
            )}
          >
            {option.label}
          </button>
        );
      })}
    </div>
  );
}
