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

import usePermissions from 'src/hooks/usePermissions';
import { UserPermissions } from 'src/utils/permissions';

const Body = styled('div')(() => ({
  fontFamily: 'Arial',
  lineHeight: '1.4',
  '& p': {
    display: 'block',
    width: '100%',
    wordWrap: 'break-word',
    margin: 'revert',
  },
  '& ul, li, ol': {
    padding: 'revert',
  },
  '& iframe, video, img': {
    maxWidth: '100%',
  },
  '& video, img': {
    height: 'auto !important',
  },
  '& img[style*="width:auto"], video[style*="width:auto"]': {
    width: 'revert-layer !important',
  },
}));

type HTMLBodyProps = {
  body: string;
  sx?: SxProps;
};

/**
 * @deprecated This component is deprecated. Please use the material-hu HTMLBody component instead.
 */
export const HTMLBody = ({ body, sx }: HTMLBodyProps) => {
  const { hasAll: canDownloadVideo } = usePermissions([
    UserPermissions.CAN_DOWNLOAD_VIDEO,
  ]);

  const sanitizedBody = DOMPurify.sanitize(body, {
    USE_PROFILES: { html: true },
    // Keep trusted embed containers that this component explicitly supports.
    ADD_TAGS: ['iframe'],
    ADD_ATTR: [
      'allow',
      'allowfullscreen',
      'frameborder',
      'scrolling',
      'sandbox',
      'referrerpolicy',
    ],
  });
  const parser = new DOMParser();
  const content = parser.parseFromString(sanitizedBody, 'text/html');
  const anchors = content.getElementsByTagName('a');
  const videos = content.getElementsByTagName('video');
  const iframes = content.getElementsByTagName('iframe');

  Array.from(anchors).forEach(a => {
    a.setAttribute('target', '_blank');
    a.setAttribute('rel', 'noreferrer');
  });

  Array.from(videos).forEach(video => {
    if (!canDownloadVideo) {
      video.setAttribute('controlslist', 'nodownload');
      video.setAttribute('oncontextmenu', 'return false');
    }
  });

  Array.from(iframes).forEach(iframe => {
    iframe.style.border = 'none';
  });

  return (
    <Body
      sx={sx}
      dangerouslySetInnerHTML={{ __html: content.body.innerHTML }}
    />
  );
};

export default HTMLBody;
