import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import isEmpty from '../../../../node_modules/lodash-es/isEmpty.js';
import _omit from '../../../../node_modules/lodash-es/omit.js';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.array.find.js';
import 'core-js/modules/es.array.find-index.js';
import 'core-js/modules/es.array.includes.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.function.name.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/es.regexp.to-string.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import React__default, { useState, useMemo } from 'react';
import PropTypes from 'prop-types';
import { v4 } from 'uuid';
import { red60 } from '@carbon/colors';
import { Dropdown, TextInput, RadioButtonGroup, RadioButton, NumberInput } from '@carbon/react';
import { settings } from '../../../../constants/Settings.js';
import Button from '../../../Button/Button.js';
import { validThresholdIcons, validThresholdColors } from '../../../DashboardEditor/editorUtils.js';
import SimpleIconDropdown from '../../../SimpleIconDropdown/SimpleIconDropdown.js';
import ColorDropdown from '../../../ColorDropdown/ColorDropdown.js';
import { CarbonIconPropType } from '../../../../constants/SharedPropTypes.js';
import { TrashCan, Add } 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,
  prefix = settings.prefix;
var propTypes = {
  /* card value */
  cardConfig: PropTypes.shape({
    id: PropTypes.string,
    title: PropTypes.string,
    size: PropTypes.string,
    type: PropTypes.string,
    content: PropTypes.shape({
      series: PropTypes.arrayOf(PropTypes.shape({
        label: PropTypes.string,
        dataSourceId: PropTypes.string,
        color: PropTypes.string
      })),
      xLabel: PropTypes.string,
      yLabel: PropTypes.string,
      unit: PropTypes.string,
      includeZeroOnXaxis: PropTypes.bool,
      includeZeroOnYaxis: PropTypes.bool,
      timeDataSourceId: PropTypes.string
    }),
    interval: PropTypes.string
  }),
  onChange: PropTypes.func,
  thresholds: PropTypes.arrayOf(PropTypes.shape({
    dataSourceId: PropTypes.string,
    comparison: PropTypes.string,
    value: PropTypes.number,
    color: PropTypes.string,
    icon: PropTypes.string
  })),
  icons: PropTypes.arrayOf(PropTypes.shape({
    carbonIcon: CarbonIconPropType,
    name: PropTypes.string,
    color: PropTypes.string
  })),
  /** default icon for each threshold */
  selectedIcon: PropTypes.shape({
    carbonIcon: CarbonIconPropType,
    name: PropTypes.string,
    color: PropTypes.string
  }),
  colors: PropTypes.arrayOf(PropTypes.shape({
    carbonColor: PropTypes.string,
    name: PropTypes.string
  })),
  /** default color for each threshold */
  selectedColor: PropTypes.shape({
    carbonColor: PropTypes.string,
    name: PropTypes.string
  }),
  i18n: PropTypes.shape({
    dataItemEditorDataItemThresholds: PropTypes.string,
    dataItemEditorDataItemAddThreshold: PropTypes.string,
    dataItemEditorDataItemRemove: PropTypes.string
  }),
  /** The current data item's id */
  dataSourceId: PropTypes.string,
  /** callback function to translate common ids */
  translateWithId: PropTypes.func,
  columnType: PropTypes.oneOf(['LITERAL', 'BOOLEAN', 'TIMESTAMP', 'NUMBER'])
};
var defaultProps = {
  dataSourceId: null,
  cardConfig: {},
  onChange: null,
  thresholds: [],
  i18n: {
    dataItemEditorDataItemThresholds: 'Thresholds',
    dataItemEditorDataItemAddThreshold: 'Add threshold',
    dataItemEditorDataItemRemove: 'Remove'
  },
  icons: validThresholdIcons,
  selectedIcon: undefined,
  colors: validThresholdColors,
  selectedColor: undefined,
  translateWithId: undefined,
  columnType: undefined
};
var booleanTypeOptions = [{
  label: 'True',
  value: true
}, {
  label: 'False',
  value: false
}];
var ThresholdsFormItem = function ThresholdsFormItem(_ref) {
  var dataSourceId = _ref.dataSourceId,
    cardConfig = _ref.cardConfig,
    thresholdsProp = _ref.thresholds,
    icons = _ref.icons,
    selectedIcon = _ref.selectedIcon,
    colors = _ref.colors,
    selectedColor = _ref.selectedColor,
    _onChange = _ref.onChange,
    i18n = _ref.i18n,
    translateWithId = _ref.translateWithId,
    columnType = _ref.columnType;
  var mergedI18n = _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  var baseClassName = "".concat(iotPrefix, "--card-edit-form");

  // initialize thresholds with a unique id
  var _useState = useState(thresholdsProp.map(function (threshold) {
      return _objectSpread(_objectSpread({}, threshold), {}, {
        id: v4()
      });
    })),
    _useState2 = _slicedToArray(_useState, 2),
    thresholds = _useState2[0],
    setThresholds = _useState2[1];
  var comparisonItems = useMemo(function () {
    return ['BOOLEAN', 'LITERAL'].includes(columnType) ? ['='] : ['>', '<', '='];
  }, [columnType]);
  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, !isEmpty(thresholds) && /*#__PURE__*/React__default.createElement("span", {
    className: "".concat(prefix, "--label ").concat(baseClassName, "--input-label")
  }, mergedI18n.dataItemEditorDataItemThresholds), thresholds.map(function (threshold, i) {
    var _threshold$value, _threshold$value2;
    // add threshold color to all icon options
    var iconsWithColors = icons.map(function (icon) {
      return _objectSpread(_objectSpread({}, icon), threshold.color ? {
        color: threshold.color
      } : {});
    });

    // add threshold color to selected icon
    var selectedThresholdIconWithColor = _objectSpread(_objectSpread({}, validThresholdIcons.find(function (icon) {
      return icon.name === threshold.icon;
    })), threshold.color ? {
      color: threshold.color
    } : {});

    // get threshold color to initialize color dropdown
    var thresholdColor = colors.find(function (color) {
      return color.carbonColor === threshold.color;
    });
    return /*#__PURE__*/React__default.createElement("div", {
      key: "".concat(threshold.id, "_").concat(i)
    }, /*#__PURE__*/React__default.createElement("div", {
      className: "".concat(baseClassName, "--threshold-input-group")
    }, /*#__PURE__*/React__default.createElement("div", {
      className: "".concat(baseClassName, "--threshold-input-group--item-dropdown")
    }, /*#__PURE__*/React__default.createElement(SimpleIconDropdown
    // need to regen if a threshold is added or color is changed
    , {
      key: "".concat(thresholds.length, "_").concat(threshold.color),
      id: "".concat(cardConfig.id, "_value-card-threshold-icon_").concat(i),
      icons: iconsWithColors,
      selectedIcon: selectedThresholdIconWithColor,
      onChange: function onChange(_ref2) {
        var icon = _ref2.icon;
        var updatedThresholds = _toConsumableArray(thresholds);
        updatedThresholds[i] = _objectSpread(_objectSpread({}, updatedThresholds[i]), {}, {
          icon: icon.name
        });
        _onChange(updatedThresholds.map(function (item) {
          return _omit(item, 'id');
        }));
        setThresholds(updatedThresholds);
      },
      translateWithId: translateWithId
    })), /*#__PURE__*/React__default.createElement("div", {
      className: "".concat(baseClassName, "--threshold-input-group--item-dropdown")
    }, /*#__PURE__*/React__default.createElement(ColorDropdown
    // need to regen if a threshold is added
    , {
      key: "".concat(thresholds.length),
      id: "".concat(cardConfig.id, "_value-card-threshold-color_").concat(i),
      label: "",
      titleText: "",
      hideLabels: true,
      colors: colors,
      selectedColor: thresholdColor,
      onChange: function onChange(_ref3) {
        var color = _ref3.color;
        var updatedThresholds = _toConsumableArray(thresholds);
        updatedThresholds[i] = _objectSpread(_objectSpread({}, updatedThresholds[i]), {}, {
          color: color.carbonColor
        });
        _onChange(updatedThresholds.map(function (item) {
          return _omit(item, 'id');
        }));
        setThresholds(updatedThresholds);
      },
      translateWithId: translateWithId
    })), /*#__PURE__*/React__default.createElement("div", {
      className: "".concat(baseClassName, "--threshold-input-group--item-dropdown")
    }, /*#__PURE__*/React__default.createElement(Dropdown
    // need to regen if a threshold is added
    , {
      key: "".concat(thresholds.length),
      id: "".concat(cardConfig.id, "_value-card-threshold-comparison_").concat(i),
      direction: "bottom",
      translateWithId: translateWithId,
      label: "",
      items: comparisonItems // current valid comparison operators
      ,
      selectedItem: threshold.comparison || comparisonItems[0],
      onChange: function onChange(_ref4) {
        var selectedItem = _ref4.selectedItem;
        var updatedThresholds = _toConsumableArray(thresholds);
        updatedThresholds[i] = _objectSpread(_objectSpread({}, updatedThresholds[i]), {}, {
          comparison: selectedItem
        });
        _onChange(updatedThresholds.map(function (item) {
          return _omit(item, 'id');
        }));
        setThresholds(updatedThresholds);
      },
      autoAlign: true
    })), /*#__PURE__*/React__default.createElement("div", {
      className: "".concat(baseClassName, "--threshold-input-group--item-end")
    }, threshold.comparison === '=' && (!columnType || columnType === 'LITERAL' || columnType === 'TIMESTAMP') ? /*#__PURE__*/React__default.createElement(TextInput, {
      "data-testid": "threshold-".concat(i, "-text-input"),
      id: "".concat(cardConfig.id, "_value-card-threshold-value_").concat(i),
      labelText: "",
      value: (_threshold$value = threshold.value) === null || _threshold$value === void 0 ? void 0 : _threshold$value.toString(),
      onChange: function onChange(_ref5) {
        var target = _ref5.target;
        var updatedThresholds = _toConsumableArray(thresholds);
        updatedThresholds[i] = _objectSpread(_objectSpread({}, updatedThresholds[i]), {}, {
          value: target.value
        });
        _onChange(updatedThresholds.map(function (item) {
          return _omit(item, 'id');
        }));
        setThresholds(updatedThresholds);
      }
    }) : threshold.comparison === '=' && columnType === 'BOOLEAN' ? /*#__PURE__*/React__default.createElement(RadioButtonGroup, {
      id: "thresold-radio-group-".concat(i, "-boolean-item"),
      name: "thresold-radio-group-".concat(i, "-boolean-item"),
      onChange: function onChange(value) {
        var updatedThresholds = _toConsumableArray(thresholds);
        updatedThresholds[i] = _objectSpread(_objectSpread({}, updatedThresholds[i]), {}, {
          value: value
        });
        _onChange(updatedThresholds.map(function (item) {
          return _omit(item, 'id');
        }));
        setThresholds(updatedThresholds);
      },
      valueSelected: threshold.value
    }, booleanTypeOptions.map(function (_ref6, index) {
      var label = _ref6.label,
        value = _ref6.value;
      return /*#__PURE__*/React__default.createElement(RadioButton, {
        key: "".concat(i, "-").concat(index),
        id: "".concat(i, "-").concat(index),
        labelText: label,
        value: value
      });
    })) : /*#__PURE__*/React__default.createElement(NumberInput, {
      id: "".concat(cardConfig.id, "_value-card-threshold-value_").concat(i),
      step: 1,
      hideLabel: true,
      translateWithId: translateWithId,
      invalid: false // don't allow invalid state
      ,
      value: ((_threshold$value2 = threshold.value) === null || _threshold$value2 === void 0 ? void 0 : _threshold$value2.toString()) || 0,
      onChange: function onChange(_ref7) {
        var value = _ref7.value;
        var updatedThresholds = _toConsumableArray(thresholds);
        updatedThresholds[i] = _objectSpread(_objectSpread({}, updatedThresholds[i]), {}, {
          value: value
        });
        _onChange(updatedThresholds.map(function (item) {
          return _omit(item, 'id');
        }));
        setThresholds(updatedThresholds);
      }
    })), /*#__PURE__*/React__default.createElement(Button, {
      hasIconOnly: true,
      renderIcon: TrashCan,
      size: "md",
      kind: "ghost",
      onClick: function onClick() {
        var thresholdIndex = thresholds.findIndex(function (item) {
          return item.id === threshold.id;
        });
        var filteredThresholds = thresholds.filter(function (item, index) {
          return index !== thresholdIndex;
        });
        _onChange(filteredThresholds.map(function (item) {
          return _omit(item, 'id');
        }));
        setThresholds(filteredThresholds);
      },
      iconDescription: mergedI18n.dataItemEditorDataItemRemove,
      tooltipPosition: "left",
      tooltipAlignment: "center"
    })));
  }), /*#__PURE__*/React__default.createElement(Button, {
    kind: "ghost",
    size: "sm",
    renderIcon: Add,
    onClick: function onClick() {
      var newThreshold = ['BOOLEAN', 'LITERAL', 'TIMESTAMP'].includes(columnType) ? {
        comparison: '=',
        value: columnType === 'BOOLEAN' ? false : '',
        color: (selectedColor === null || selectedColor === void 0 ? void 0 : selectedColor.carbonColor) || red60
      } : {
        comparison: '>',
        value: 0,
        color: (selectedColor === null || selectedColor === void 0 ? void 0 : selectedColor.carbonColor) || red60
      };
      if (selectedIcon !== null && selectedIcon !== void 0 && selectedIcon.name) {
        newThreshold.icon = selectedIcon.name;
      }
      if (dataSourceId) {
        newThreshold = _objectSpread({
          dataSourceId: dataSourceId
        }, newThreshold);
      }
      setThresholds([].concat(_toConsumableArray(thresholds), [_objectSpread({
        id: v4()
      }, newThreshold)]));
      _onChange([].concat(_toConsumableArray(thresholds), [newThreshold]));
    }
  }, mergedI18n.dataItemEditorDataItemAddThreshold));
};
ThresholdsFormItem.defaultProps = defaultProps;
ThresholdsFormItem.propTypes = propTypes;
ThresholdsFormItem.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "ThresholdsFormItem",
  "props": {
    "dataSourceId": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "The current data item's id",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "cardConfig": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "id": {
            "name": "string",
            "required": false
          },
          "title": {
            "name": "string",
            "required": false
          },
          "size": {
            "name": "string",
            "required": false
          },
          "type": {
            "name": "string",
            "required": false
          },
          "content": {
            "name": "shape",
            "value": {
              "series": {
                "name": "arrayOf",
                "value": {
                  "name": "shape",
                  "value": {
                    "label": {
                      "name": "string",
                      "required": false
                    },
                    "dataSourceId": {
                      "name": "string",
                      "required": false
                    },
                    "color": {
                      "name": "string",
                      "required": false
                    }
                  }
                },
                "required": false
              },
              "xLabel": {
                "name": "string",
                "required": false
              },
              "yLabel": {
                "name": "string",
                "required": false
              },
              "unit": {
                "name": "string",
                "required": false
              },
              "includeZeroOnXaxis": {
                "name": "bool",
                "required": false
              },
              "includeZeroOnYaxis": {
                "name": "bool",
                "required": false
              },
              "timeDataSourceId": {
                "name": "string",
                "required": false
              }
            },
            "required": false
          },
          "interval": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "onChange": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "thresholds": {
      "defaultValue": {
        "value": "[]",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "shape",
          "value": {
            "dataSourceId": {
              "name": "string",
              "required": false
            },
            "comparison": {
              "name": "string",
              "required": false
            },
            "value": {
              "name": "number",
              "required": false
            },
            "color": {
              "name": "string",
              "required": false
            },
            "icon": {
              "name": "string",
              "required": false
            }
          }
        }
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  dataItemEditorDataItemThresholds: 'Thresholds',\n  dataItemEditorDataItemAddThreshold: 'Add threshold',\n  dataItemEditorDataItemRemove: 'Remove',\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "dataItemEditorDataItemThresholds": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDataItemAddThreshold": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDataItemRemove": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "icons": {
      "defaultValue": {
        "value": "validThresholdIcons",
        "computed": true
      },
      "description": "",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "shape",
          "value": {
            "carbonIcon": {
              "name": "custom",
              "raw": "CarbonIconPropType",
              "required": false
            },
            "name": {
              "name": "string",
              "required": false
            },
            "color": {
              "name": "string",
              "required": false
            }
          }
        }
      },
      "required": false
    },
    "selectedIcon": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "default icon for each threshold",
      "type": {
        "name": "shape",
        "value": {
          "carbonIcon": {
            "name": "custom",
            "raw": "CarbonIconPropType",
            "required": false
          },
          "name": {
            "name": "string",
            "required": false
          },
          "color": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "colors": {
      "defaultValue": {
        "value": "validThresholdColors",
        "computed": true
      },
      "description": "",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "shape",
          "value": {
            "carbonColor": {
              "name": "string",
              "required": false
            },
            "name": {
              "name": "string",
              "required": false
            }
          }
        }
      },
      "required": false
    },
    "selectedColor": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "default color for each threshold",
      "type": {
        "name": "shape",
        "value": {
          "carbonColor": {
            "name": "string",
            "required": false
          },
          "name": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "translateWithId": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "callback function to translate common ids",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "columnType": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "",
      "type": {
        "name": "enum",
        "value": [{
          "value": "'LITERAL'",
          "computed": false
        }, {
          "value": "'BOOLEAN'",
          "computed": false
        }, {
          "value": "'TIMESTAMP'",
          "computed": false
        }, {
          "value": "'NUMBER'",
          "computed": false
        }]
      },
      "required": false
    }
  }
};
var ThresholdsFormItem$1 = ThresholdsFormItem;

export { ThresholdsFormItem$1 as default };
