import React from 'react';
import parse, { HTMLReactParserOptions } from 'html-react-parser';
import Linkify from 'linkify-react';
import { Opts } from 'linkifyjs';
import { MessageEmptyContent } from './content';
import { sanitizeCustomHtml } from '../../utils/sanitize';
import { highlightText, scaleSystemEmoji } from '../../plugins/react-custom-html-parser';
import { isMxEmoticonOnlyHtml } from '../../utils/regex';
// Ensure jumbo emoji global styles are always in the bundle.
import './layout/layout.css';

type RenderBodyProps = {
  body: string;
  customBody?: string;
  jumbo?: boolean;

  highlightRegex?: RegExp;
  htmlReactParserOptions: HTMLReactParserOptions;
  jumboHtmlReactParserOptions?: HTMLReactParserOptions;
  linkifyOpts: Opts;
};
export function RenderBody({
  body,
  customBody,
  jumbo = false,
  highlightRegex,
  htmlReactParserOptions,
  jumboHtmlReactParserOptions,
  linkifyOpts,
}: RenderBodyProps) {
  const hasCustomBody = typeof customBody === 'string' && customBody.length > 0;
  // Unicode jumbo should use the plain path so scaleSystemEmoji gets the jumbo flag.
  // HTML path is only needed for custom mx-emoticon images.
  const useCustomHtml = hasCustomBody && (!jumbo || isMxEmoticonOnlyHtml(customBody));

  if (useCustomHtml) {
    const options =
      jumbo && jumboHtmlReactParserOptions ? jumboHtmlReactParserOptions : htmlReactParserOptions;
    return parse(sanitizeCustomHtml(customBody), options);
  }

  if (body === '') return <MessageEmptyContent />;

  return (
    <Linkify options={linkifyOpts}>
      {highlightRegex
        ? highlightText(highlightRegex, scaleSystemEmoji(body, jumbo))
        : scaleSystemEmoji(body, jumbo)}
    </Linkify>
  );
}
