import { observer } from 'mobx-react';
import React from 'react';
import { useApphouse } from '../context/useApphouse';

type TextHighlighterProps = {
  /**
   * The text to be highlighted
   */
  input: string;
  /**
   * The start index of the text to be highlighted
   * @default 0
   */
  startIndex?: number;
  /**
   * The end index of the text to be highlighted
   * @default 0
   */
  endIndex?: number;
  /**
   * A style in css string format to be applied to the highlighted text
   * @default 'background-color: #FFC107; color: #000000; border-radius: 4px; font-family: inherit; font-size: inherit;'
   *
   */
  highlightStyle?: string;
};

/**
 * A component that highlights a portion of text
 */
export const TextHighlighter: React.FC<TextHighlighterProps> = observer(
  ({ input, startIndex = 0, endIndex = 0, highlightStyle }) => {
    const { theme } = useApphouse();
    const { colors } = theme;

    const _input = input + ' ';
    const style =
      highlightStyle ||
      `background-color: ${colors.brand}; color: ${colors.onBrand}; border-radius: 4px; font-family: inherit; font-size: inherit;`;
    const highlightedText =
      _input.slice(0, startIndex) +
      `<span style="${style}">` +
      _input.slice(startIndex, endIndex) +
      '</span>' +
      _input.slice(endIndex);

    return <div dangerouslySetInnerHTML={{ __html: highlightedText }} />;
  }
);
