import { SVGProps, forwardRef } from 'react';

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

import { StyledSpan, StyledSpanWithAction, TunedIcon } from './styled';

export interface IconHelpProps extends Omit<CommonProps, 'ariaDescribedBy'> {
  ariaLabel?: SVGProps<SVGSVGElement>['aria-label'];
  /** Hint text of tooltip. */
  hintText: string;
  /** Action on click */
  onClick?: () => void;
}

/**
 *  Icon help is a specifically stylized atom used in different places of the application
 *  to provide a consistent look for broadly used hint triggers.
 */
export const IconHelp = forwardRef<HTMLSpanElement, IconHelpProps>((props: IconHelpProps, ref) => {
  const { hintText, onClick, ariaLabel, className, testId, ...rest } = props;
  assertEmptyObject(rest);

  const testIdAttribute = useTestIdAttribute();

  let component;
  if (onClick) {
    component = (
      <StyledSpanWithAction
        ref={ref}
        aria-label={ariaLabel}
        className={className}
        onClick={onClick}
        role="button"
        tabIndex={0}
        {...{ [testIdAttribute]: testId }}
      >
        <TunedIcon glyph={IconGlyph.HelpSolid} />
      </StyledSpanWithAction>
    );
  } else {
    component = (
      <StyledSpan ref={ref} aria-label={ariaLabel} className={className} {...{ [testIdAttribute]: testId }}>
        <TunedIcon glyph={IconGlyph.HelpSolid} />
      </StyledSpan>
    );
  }

  return (
    <Tooltip position={TooltipPosition.Top} text={hintText}>
      {component}
    </Tooltip>
  );
});
