import { type FC } from 'react';

import DOMPurify from 'dompurify';
import { type SxProps } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import { decodeHtmlEntities } from 'src/utils/html';

import {
  processLinksToOpenInNewTab,
  processListStyles,
  unwrapListItemParagraphs,
} from './utils';

type RichTextProps = {
  text: string;
  sx?: SxProps;
  openLinksInNewTab?: boolean;
  decodeEntities?: boolean;
};

const RichText: FC<RichTextProps> = props => {
  const { text, sx, openLinksInNewTab = false, decodeEntities = false } = props;

  const content = decodeEntities ? decodeHtmlEntities(text) : text;
  let processedText = DOMPurify.sanitize(content, {
    USE_PROFILES: { html: true },
  });
  processedText = unwrapListItemParagraphs(processedText);
  processedText = processListStyles(processedText);
  if (openLinksInNewTab) {
    processedText = processLinksToOpenInNewTab(processedText);
  }

  return (
    <Typography
      component="div"
      sx={{
        mb: '8px',
        ...sx,
      }}
      variant="body1"
      // biome-ignore lint/security/noDangerouslySetInnerHtml: Out of scope of this refactor
      dangerouslySetInnerHTML={{
        __html: processedText,
      }}
    />
  );
};

export default RichText;
