import { jsx } from 'react/jsx-runtime';
import { isEqual } from 'lodash';
import { useState, useEffect } from 'react';
import '@grafana/data';
import { EditorField } from '../../QueryEditor/EditorField.js';
import { EditorFieldGroup } from '../../QueryEditor/EditorFieldGroup.js';
import { EditorList } from '../../QueryEditor/EditorList.js';
import { LabelFilterItem } from './LabelFilterItem.js';

const MISSING_LABEL_FILTER_ERROR_MESSAGE = "Select at least 1 label filter (label and value)";
function LabelFilters({
  labelsFilters,
  onChange,
  onGetLabelNames,
  onGetLabelValues,
  labelFilterRequired,
  multiValueSeparator
}) {
  const defaultOp = "=";
  const [items, setItems] = useState([{ op: defaultOp }]);
  useEffect(() => {
    if (labelsFilters.length > 0) {
      setItems(labelsFilters);
    } else {
      setItems([{ op: defaultOp }]);
    }
  }, [labelsFilters]);
  const onLabelsChange = (newItems) => {
    setItems(newItems);
    const newLabels = newItems.filter(
      (item) => item.label !== undefined && item.value !== undefined
    );
    if (!isEqual(newLabels, labelsFilters)) {
      onChange(newLabels);
    }
  };
  const hasLabelFilter = items.some((item) => item.label && item.value);
  return /* @__PURE__ */ jsx(EditorFieldGroup, { children: /* @__PURE__ */ jsx(
    EditorField,
    {
      label: "Label filters",
      error: MISSING_LABEL_FILTER_ERROR_MESSAGE,
      invalid: labelFilterRequired && !hasLabelFilter,
      children: /* @__PURE__ */ jsx(
        EditorList,
        {
          items,
          onChange: onLabelsChange,
          renderItem: (item, onChangeItem, onDelete) => /* @__PURE__ */ jsx(
            LabelFilterItem,
            {
              item,
              items,
              defaultOp,
              onChange: onChangeItem,
              onDelete,
              onGetLabelNames,
              onGetLabelValues,
              invalidLabel: labelFilterRequired && !item.label,
              invalidValue: labelFilterRequired && !item.value,
              multiValueSeparator
            }
          )
        }
      )
    }
  ) });
}

export { LabelFilters, MISSING_LABEL_FILTER_ERROR_MESSAGE };
//# sourceMappingURL=LabelFilters.js.map
