import { clsx } from 'clsx';
import { useId } from 'react';
import Header from '../../../../header';
import Section from '../../../../section';
import { SelectInputGroupItem } from '../../SelectInput.types';
import { SelectInputItemView, SelectInputItemViewProps } from '..';

export interface SelectInputGroupItemViewProps<T = string> extends SelectInputItemViewProps<
  T,
  SelectInputGroupItem<T | undefined>
> {}

/**
 * Component that renders a group of SelectInput options with a header.
 */
export function SelectInputGroupItemView<T = string>({
  item,
  renderValue,
  needle,
}: SelectInputGroupItemViewProps<T>) {
  const headerId = useId();

  const header = (
    <Header
      as="header"
      role="none"
      id={headerId}
      title={item.label}
      // @ts-expect-error when we migrate ActionButton to new Button this should be sorted
      action={
        item.action && {
          text: item.action.label,
          onClick: item.action.onClick,
        }
      }
      className="np-select-input-group-item-header p-x-1"
    />
  );

  return (
    // An empty container may be rendered when no options match `needle`
    // However, pre-filtering would result in worse performance overall
    <Section
      as="section"
      role="group"
      aria-labelledby={headerId}
      className={clsx('m-y-0', needle === null && 'np-select-input-group-item--without-needle')}
    >
      {needle == null ? header : null}
      {item.options.map((option, index) => (
        <SelectInputItemView
          // eslint-disable-next-line react/no-array-index-key
          key={index}
          item={option}
          renderValue={renderValue}
          needle={needle}
        />
      ))}
    </Section>
  );
}
