import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import isEmpty from '../../node_modules/lodash-es/isEmpty.js';
import isNil from '../../node_modules/lodash-es/isNil.js';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.symbol.description.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.array.iterator.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.object.get-own-property-descriptor.js';
import 'core-js/modules/es.object.get-own-property-descriptors.js';
import 'core-js/modules/es.object.keys.js';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import 'core-js/modules/web.dom-collections.iterator.js';
import React__default, { useState, useRef, useMemo } from 'react';
import { TextInput } from '@carbon/react';
import { findMatchingThresholds, formatNumberWithPrecision } from '../../utils/cardUtilityFunctions.js';
import { settings } from '../../constants/Settings.js';
import { HotspotContentPropTypes } from '../../constants/SharedPropTypes.js';
import CardIcon from './CardIcon.js';
import { Edit } from '@carbon/icons-react';

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var iotPrefix = settings.iotPrefix;
var propTypes = HotspotContentPropTypes;
var defaultProps = {
  title: null,
  i18n: {
    titlePlaceholderText: 'Enter label',
    titleEditableHintText: 'Click to edit label'
  },
  description: null,
  values: {},
  attributes: [],
  hotspotThreshold: null,
  renderIconByName: null,
  locale: 'en',
  isTitleEditable: false,
  id: 'hotspot-content',
  onChange: function onChange() {}
};

/**
 * This component renders a form for editing Text Hotspot contents
 */
var HotspotContent = function HotspotContent(_ref) {
  var title = _ref.title,
    i18n = _ref.i18n,
    description = _ref.description,
    attributes = _ref.attributes,
    values = _ref.values,
    hotspotThreshold = _ref.hotspotThreshold,
    locale = _ref.locale,
    renderIconByName = _ref.renderIconByName,
    isTitleEditable = _ref.isTitleEditable,
    id = _ref.id,
    onChange = _ref.onChange;
  var _useState = useState(isTitleEditable && !title),
    _useState2 = _slicedToArray(_useState, 2),
    showTitleInput = _useState2[0],
    setShowTitleInput = _useState2[1];
  var titleInputFocusRef = useRef(null);
  var _useState3 = useState(title),
    _useState4 = _slicedToArray(_useState3, 2),
    titleValue = _useState4[0],
    setTitleValue = _useState4[1];
  if (showTitleInput && titleInputFocusRef.current) {
    titleInputFocusRef.current.focus();
  }
  var mergedI18n = useMemo(function () {
    return _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  }, [i18n]);
  var titlePlaceholderText = mergedI18n.titlePlaceholderText,
    titleEditableHintText = mergedI18n.titleEditableHintText;
  var renderTitle = function renderTitle() {
    var titleEditableTextVersion =
    /*#__PURE__*/
    // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions
    React__default.createElement("h4", {
      onClick: function onClick() {
        return setShowTitleInput(isTitleEditable);
      },
      title: titleEditableHintText
    }, titleValue !== null && titleValue !== '' ? titleValue : /*#__PURE__*/React__default.createElement(Edit, {
      size: 20
    }));
    var titleFixedTextVersion = /*#__PURE__*/React__default.createElement("h4", {
      title: title,
      className: "".concat(iotPrefix, "--hotspot-content-fixed-title")
    }, title);
    var titleInputVersion = /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("div", {
      className: "".concat(iotPrefix, "--hotspot-content-title-wrapper--editable")
    }, /*#__PURE__*/React__default.createElement(TextInput, {
      className: "".concat(iotPrefix, "--hotspot-content-title-input"),
      defaultValue: typeof title === 'string' ? title : '',
      id: "".concat(id, "-title"),
      "data-testid": "".concat(id, "-title-test"),
      ref: titleInputFocusRef,
      onChange: function onChange(evt) {
        setTitleValue(evt.currentTarget.value);
      },
      onBlur: function onBlur(evt) {
        var latestValue = evt.currentTarget.value;
        setShowTitleInput(false);
        if (title !== latestValue) {
          onChange({
            title: latestValue
          });
        }
      },
      labelText: "",
      placeholder: titlePlaceholderText
    })),
    /*#__PURE__*/
    // We still render the non editable title but as visually hidden so that the width will be
    // correctly modified as we type in the TextInput.
    React__default.createElement("h4", {
      className: "".concat(iotPrefix, "--hotspot-content-title__visually-hidden")
    }, titleValue));
    return typeof title === 'string' && showTitleInput ? titleInputVersion : typeof title === 'string' && isTitleEditable ? titleEditableTextVersion : typeof title === 'string' ? titleFixedTextVersion : /*#__PURE__*/React__default.isValidElement(title) ? title : null;
  };
  return /*#__PURE__*/React__default.createElement("div", {
    className: "".concat(iotPrefix, "--hotspot-content")
  }, renderTitle(), description && /*#__PURE__*/React__default.createElement("p", {
    className: "".concat(iotPrefix, "--hotspot-content-description")
  }, description), attributes.map(function (_ref2) {
    var thresholds = _ref2.thresholds,
      dataSourceId = _ref2.dataSourceId,
      label = _ref2.label,
      unit = _ref2.unit,
      precision = _ref2.precision;
    // look for attribute specific thresholds first
    var attributeThresholdMatch = null;
    if (!isEmpty(thresholds)) {
      var matchingAttributeThresholds = findMatchingThresholds(thresholds.map(function (threshold) {
        return _objectSpread(_objectSpread({}, threshold), {}, {
          dataSourceId: dataSourceId
        });
      }), values, dataSourceId);
      if (matchingAttributeThresholds && !isEmpty(matchingAttributeThresholds)) {
        var _matchingAttributeThr = _slicedToArray(matchingAttributeThresholds, 1);
        attributeThresholdMatch = _matchingAttributeThr[0];
      }
    }
    var thresholdMatch = attributeThresholdMatch || (hotspotThreshold && hotspotThreshold.dataSourceId === dataSourceId // then see if the parent threshold might match this attribute
    ? hotspotThreshold : null);
    var value = isNil(values === null || values === void 0 ? void 0 : values[dataSourceId]) ? '--' : values[dataSourceId];
    var thresholdIcon = thresholdMatch && thresholdMatch.dataSourceId === dataSourceId && thresholdMatch.icon ? /*#__PURE__*/React__default.createElement(CardIcon, {
      icon: thresholdMatch.icon,
      color: thresholdMatch.color,
      title: "".concat(thresholdMatch.dataSourceId, " ").concat(thresholdMatch.comparison, " ").concat(typeof thresholdMatch.value === 'number' ? formatNumberWithPrecision(thresholdMatch.value, null, locale) : thresholdMatch.value),
      width: 16,
      height: 16,
      renderIconByName: renderIconByName
    }) : null;
    return /*#__PURE__*/React__default.createElement("div", {
      key: "attribute-".concat(dataSourceId),
      className: "".concat(iotPrefix, "--hotspot-content-attribute")
    }, /*#__PURE__*/React__default.createElement("div", {
      className: "".concat(iotPrefix, "--hotspot-content-label-section")
    }, /*#__PURE__*/React__default.createElement("span", {
      className: "".concat(iotPrefix, "--hotspot-content-label")
    }, label, ":")), /*#__PURE__*/React__default.createElement("div", {
      className: "".concat(iotPrefix, "--hotspot-content-threshold-section")
    }, thresholdIcon, /*#__PURE__*/React__default.createElement("span", {
      style: {
        '--threshold-color': !thresholdIcon && thresholdMatch ? thresholdMatch.color : 'inherit ',
        '--threshold-padding': thresholdIcon ? '0.25rem' : '0rem'
      },
      className: "".concat(iotPrefix, "--hotspot-content-threshold")
    }, typeof value === 'number' ? formatNumberWithPrecision(value, !isNil(precision) ? precision : Math.abs(value) < 1 ? value === 0 ? 0 : 3 // for small decimals give 3 spots
    : 1,
    // otherwise 1 spot if precision isn't set
    locale) : typeof value === 'boolean' ? String(value) : value, unit && value !== '--' && /*#__PURE__*/React__default.createElement("span", {
      className: "".concat(iotPrefix, "--hotspot-content-unit")
    }, unit))));
  }));
};
HotspotContent.propTypes = propTypes;
HotspotContent.defaultProps = defaultProps;
HotspotContent.__docgenInfo = {
  "description": "This component renders a form for editing Text Hotspot contents",
  "methods": [],
  "displayName": "HotspotContent",
  "props": {
    "title": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  titlePlaceholderText: 'Enter label',\n  titleEditableHintText: 'Click to edit label',\n}",
        "computed": false
      },
      "required": false
    },
    "description": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "required": false
    },
    "values": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "required": false
    },
    "attributes": {
      "defaultValue": {
        "value": "[]",
        "computed": false
      },
      "required": false
    },
    "hotspotThreshold": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "required": false
    },
    "renderIconByName": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "required": false
    },
    "locale": {
      "defaultValue": {
        "value": "'en'",
        "computed": false
      },
      "required": false
    },
    "isTitleEditable": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "required": false
    },
    "id": {
      "defaultValue": {
        "value": "'hotspot-content'",
        "computed": false
      },
      "required": false
    },
    "onChange": {
      "defaultValue": {
        "value": "() => {}",
        "computed": false
      },
      "required": false
    }
  },
  "composes": ["../../constants/SharedPropTypes"]
};
var HotspotContent$1 = HotspotContent;

export { HotspotContent$1 as default };
