import { type FC } from 'react';

import DOMPurify from 'dompurify';
import Dialog from '@material-hu/mui/Dialog';
import DialogActions from '@material-hu/mui/DialogActions';
import DialogContent from '@material-hu/mui/DialogContent';
import DialogTitle from '@material-hu/mui/DialogTitle';
import { styled } from '@material-hu/mui/styles';

import Button from '@material-hu/components/design-system/Buttons/Button';

import { useTranslation } from 'src/pages/dashboard/tickets/i18n';

const Body = styled('div')({
  '& p': {
    display: 'block',
    width: '100%',
    wordWrap: 'break-word',
    padding: 'revert',
    margin: 'revert',
  },
  '& img': {
    display: 'block',
    marginBottom: '30px',
    maxWidth: '100%',
    height: 'auto',
  },
  '& ul, li, ol': {
    padding: 'revert',
  },
});

type FAQDialogProps = {
  open: boolean;
  onClose?: () => void;
  body: string;
};

const FAQDialog: FC<FAQDialogProps> = props => {
  const { open, onClose, body } = props;

  const { t } = useTranslation();

  const parser = new DOMParser();
  const content = parser.parseFromString(
    DOMPurify.sanitize(body, {
      USE_PROFILES: { html: true },
    }),
    'text/html',
  );
  const anchors = content.getElementsByTagName('a');

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

  return (
    <Dialog
      open={open}
      onClose={onClose}
    >
      <DialogTitle>{t('FAQ')}</DialogTitle>
      <DialogContent>
        <Body dangerouslySetInnerHTML={{ __html: content.body.innerHTML }} />
      </DialogContent>
      <DialogActions>
        <Button
          onClick={onClose}
          color="primary"
          variant="contained"
          type="button"
        >
          {t('ACCEPT')}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default FAQDialog;
