import { forwardRef, useEffect } from 'react';
import { useEffectEvent } from '../../../../common/hooks/useEffectEvent';

export interface SelectInputOptionsContainerProps extends React.ComponentPropsWithRef<'div'> {
  onAriaActiveDescendantChange: (value: React.AriaAttributes['aria-activedescendant']) => void;
}

/**
 * Container component for SelectInput options.
 * Handles keyboard navigation and accessibility features.
 */
export const SelectInputOptionsContainer = forwardRef(function SelectInputOptionsContainer(
  {
    'aria-orientation': ariaOrientation,
    'aria-activedescendant': ariaActiveDescendant,
    role,
    tabIndex,
    onAriaActiveDescendantChange,
    onKeyDown,
    ...restProps
  }: SelectInputOptionsContainerProps,
  ref: React.ForwardedRef<HTMLDivElement | null>,
) {
  const handleAriaActiveDescendantChange = useEffectEvent(onAriaActiveDescendantChange);
  useEffect(() => {
    handleAriaActiveDescendantChange(ariaActiveDescendant);
  }, [ariaActiveDescendant, handleAriaActiveDescendantChange]);

  return (
    <div
      ref={ref}
      role="none"
      onKeyDown={(event) => {
        // Prevent confirmation close without an active item
        if (event.key === 'Enter' && ariaActiveDescendant == null) {
          return;
        }

        // Required to make ListBox focusable
        if (event.key === 'Tab') {
          return;
        }

        // Prevent absorbing Escape early
        if (event.key === 'Escape') {
          onKeyDown?.({
            ...event,
            preventDefault: () => {},
            stopPropagation: () => {},
          });
          return;
        }

        onKeyDown?.(event);
      }}
      {...restProps}
    />
  );
});
