import React, { useMemo } from "react";
import { getHighlightFragments } from "@tingwu/common";

export interface HighlightTextProps {
  text: string;
  keyword: string;
  highlightStyle?: React.CSSProperties;
  highlightClassName?: string;
  inline?: boolean;
  className?: string;
  style?: React.CSSProperties;
}

export const HighlightText: React.FC<HighlightTextProps> = props => {
  const {
    text,
    keyword,
    highlightStyle,
    highlightClassName,
    inline = false,
    className,
    style = {},
    ...restProps
  } = props;

  const fragments = useMemo(() => getHighlightFragments(text, keyword), [text, keyword]);

  const calcStyle = useMemo(() => {
    return {
      ...style,
      display: inline ? "inline" : "block",
    };
  }, [style, inline]);

  return (
    <div className={className} style={calcStyle} {...restProps}>
      {fragments.map(({ title: _title, isKeyword }, index) => {
        if (isKeyword) {
          return (
            <span style={highlightStyle} className={highlightClassName} key={`${_title}_${index}`}>
              {_title}
            </span>
          );
        }
        return _title;
      })}
    </div>
  );
};
