import React from "react";

import { uniqueId } from "lodash";
import ReactTooltip from "react-tooltip";

import { DEFAULT_EMPTY_CELL_VALUE } from "utilities/constants";
import { formatFloatAsPercentage } from "utilities/helpers";

import Icon from "components/Icon";
import { COLORS } from "styles/var/colors";

const baseClass = "probability-of-exploit";

interface IProbabilityOfExploit {
  probabilityOfExploit?: number | null;
  cisaKnownExploit?: boolean | null;
  tooltipPosition?: "top" | "bottom" | "left" | "right";
}

const ProbabilityOfExploit = ({
  probabilityOfExploit,
  cisaKnownExploit,
  tooltipPosition = "top",
}: IProbabilityOfExploit): JSX.Element => {
  // Grey out if API returns null or undefined (but not 0)
  if (typeof probabilityOfExploit !== "number") {
    return (
      <span className={`${baseClass}__unknown`}>
        {DEFAULT_EMPTY_CELL_VALUE}
      </span>
    );
  }

  const renderExploitedIcon = () => {
    const tooltipId = uniqueId();
    return (
      <>
        <span
          className={`${baseClass} tooltip tooltip__tooltip-icon`}
          data-tip
          data-for={tooltipId}
        >
          <Icon name="error" size="small" color="status-error" />
        </span>

        <ReactTooltip
          place={tooltipPosition}
          effect="solid"
          backgroundColor={COLORS["tooltip-bg"]}
          id={tooltipId}
          data-html
        >
          <span className={`tooltip__tooltip-text`}>
            <>
              The vulnerability has been actively exploited in the wild. This
              data is reported by the Cybersecurity and Infrastructure Security
              Agency (CISA).
            </>
          </span>
        </ReactTooltip>
      </>
    );
  };

  return (
    <span className={baseClass}>
      {formatFloatAsPercentage(probabilityOfExploit)}
      {cisaKnownExploit && renderExploitedIcon()}
    </span>
  );
};

export default ProbabilityOfExploit;
