import { Check } from '@transferwise/icons';
import { clsx } from 'clsx';
import { useContext } from 'react';
import { ListboxOption } from '@headlessui/react';
import {
  SelectInputItemsCountContext,
  SelectInputItemPositionContext,
} from '../SelectInput.contexts';

export interface SelectInputOptionProps<T = string> {
  value: T;
  disabled?: boolean;
  children?: React.ReactNode;
}

/**
 * A selectable option in a SelectInput dropdown.
 * Includes accessibility support and styling for selected, active, and disabled states.
 */
export function SelectInputOption<T = string>({
  value,
  disabled,
  children,
}: SelectInputOptionProps<T>) {
  const itemsCount = useContext(SelectInputItemsCountContext);
  const itemPosition = useContext(SelectInputItemPositionContext);

  return (
    <ListboxOption
      as="div"
      value={value}
      aria-setsize={itemsCount}
      aria-posinset={itemPosition}
      disabled={disabled}
      className={({ active, disabled: uiDisabled }) =>
        clsx(
          'np-select-input-option-container np-text-body-large',
          active && 'np-select-input-option-container--active',
          uiDisabled && 'np-select-input-option-container--disabled',
        )
      }
    >
      {({ selected }) => (
        <>
          <div className="np-select-input-option">{children}</div>
          <Check
            size={16}
            className={clsx(
              'np-select-input-option-check',
              !selected && 'np-select-input-option-check--not-selected',
            )}
          />
        </>
      )}
    </ListboxOption>
  );
}
