import React from 'react';
import { Link } from 'react-router-dom';
import { OverlayTrigger, Tooltip } from 'react-bootstrap';
import * as Icons from '@phosphor-icons/react';
import DOMPurify from 'dompurify';

function ConfigurableIcon({ 
  customClassName,
  iconName, 
  linkAddress,
  onClick,
  placement,
  simpleIcon,
  size,
  styles,
  toolTipTitle,
  suffix // Allow rendering sanitized HTML
}) {
  
  // Fallback for missing tooltip title
  if (!toolTipTitle) {
    toolTipTitle = 'no tooltip!!';
  }

  // Resolve the requested icon or fallback to a default
  const IconComponent = Icons[iconName] || Icons['Question'];

  // Prepare icon props
  const iconProps = {
    ...size && { size },
    ...styles && { style: styles },
  };

  // Sanitize suffix if provided
  const sanitizedSuffix = suffix ? DOMPurify.sanitize(suffix) : null;

  // Render the icon and suffix (simpleIcon mode)
  if (simpleIcon) {
    return (
      <span style={styles} className={customClassName}>
        <IconComponent {...iconProps} />
        {suffix && (
          <span dangerouslySetInnerHTML={{ __html: sanitizedSuffix }}></span>
        )}
      </span>
    );
  }

  return (
    <OverlayTrigger
      delay={{ hide: 100, show: 200 }}
      overlay={(
        <Tooltip>
          {toolTipTitle}
        </Tooltip>
      )}
      placement={placement || 'bottom'}
    >
      {linkAddress ? (
        // Render a Link if linkAddress is provided
        <Link
          to={linkAddress}
          className={customClassName ? customClassName : 'float-right ml-05'}
          style={styles}
        >
          <IconComponent {...iconProps} />
          {suffix && (
            <span dangerouslySetInnerHTML={{ __html: sanitizedSuffix }}></span>
          )}
        </Link>
      ) : (
        // Render a clickable div or standalone icon
        <div
          className={customClassName ? customClassName : 'float-right ml-05'}
          onClick={onClick}
          role={onClick ? 'button' : undefined} // Accessibility improvement
          style={styles}
        >
          <IconComponent {...iconProps} />
          {suffix && (
            <span dangerouslySetInnerHTML={{ __html: sanitizedSuffix }}></span>
          )}
        </div>
      )}
    </OverlayTrigger>
  );
}

export default ConfigurableIcon;