import { ReactElement } from 'react';

import { useTestIdAttribute } from '../../hooks/useTestIdAttribute';
import { CommonProps } from '../../types';
import { assertEmptyObject } from '../../utils/assertEmptyObject';
import { IconGlyph } from '../Icon/constants';

import { StyledContainer, TunedIcon } from './styled';

/** Props for {@link FieldPrefixIcon} */
export interface FieldPrefixIconProps extends CommonProps {
  /** Icon that should be displayed */
  icon: IconGlyph | ReactElement;
}

/**
 * An icon that can be added as a prefix to fields that have the property `prefix`
 *
 * ```tsx
 * <TextField
 *   prefix={<FieldPrefixIcon icon={IconGlyph.Search} />}
 * />
 * ```
 * ```tsx
 * <NumberField
 *   prefix={<FieldPrefixIcon icon={IconGlyph.Search} />}
 * />
 * ```
 */
export function FieldPrefixIcon(props: FieldPrefixIconProps) {
  const { icon, className, testId, ariaDescribedBy, ...rest } = props;
  assertEmptyObject(rest);

  const testIdAttribute = useTestIdAttribute();

  if (!icon) {
    return null;
  }

  return (
    <StyledContainer
      aria-describedby={ariaDescribedBy}
      className={className}
      {...{ [testIdAttribute]: testId }}
    >
      {typeof icon === 'string' ? <TunedIcon glyph={icon} /> : icon}
    </StyledContainer>
  );
}
