"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FieldValueSelection = FieldValueSelection;
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _lodash = require("lodash");
var _common = require("@kbn/kibana-react-plugin/common");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const Counter = _common.euiStyled.div`
  border-radius: ${({
  theme
}) => theme.eui.euiBorderRadius};
  background: ${({
  theme
}) => theme.eui.euiColorLightShade};
  padding: 0 ${({
  theme
}) => theme.eui.euiSizeXS};
`;
const formatOptions = (values, selectedValue, excludedValues, showCount) => {
  const uniqueValues = {};
  values === null || values === void 0 ? void 0 : values.forEach(({
    label,
    count
  }) => {
    uniqueValues[label] = count;
  });
  return Object.entries(uniqueValues).map(([label, count]) => ({
    label,
    append: showCount ? /*#__PURE__*/_react.default.createElement(Counter, null, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
      size: "xs"
    }, count)) : null,
    ...(selectedValue !== null && selectedValue !== void 0 && selectedValue.includes(label) ? {
      checked: 'on'
    } : {}),
    ...(excludedValues !== null && excludedValues !== void 0 && excludedValues.includes(label) ? {
      checked: 'off'
    } : {})
  }));
};
function FieldValueSelection({
  fullWidth,
  label,
  loading,
  query,
  setQuery,
  button,
  width,
  forceOpen,
  setForceOpen,
  anchorPosition,
  singleSelection,
  asFilterButton,
  showCount = true,
  values = [],
  selectedValue,
  excludedValue,
  allowExclusions = true,
  compressed = true,
  useLogicalAND,
  showLogicalConditionSwitch = false,
  onChange: onSelectionChange
}) {
  const {
    euiTheme
  } = (0, _eui.useEuiTheme)();
  const [options, setOptions] = (0, _react.useState)(() => formatOptions(values, selectedValue, excludedValue, showCount));
  const [isPopoverOpen, setIsPopoverOpen] = (0, _react.useState)(false);
  const [isLogicalAND, setIsLogicalAND] = (0, _react.useState)(useLogicalAND);
  (0, _react.useEffect)(() => {
    setIsLogicalAND(useLogicalAND);
  }, [useLogicalAND]);
  (0, _react.useEffect)(() => {
    setOptions(formatOptions(values, selectedValue, excludedValue, showCount));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [JSON.stringify(values), JSON.stringify(selectedValue), showCount, excludedValue]);
  const onButtonClick = () => {
    setIsPopoverOpen(!isPopoverOpen);
  };
  const closePopover = () => {
    setIsPopoverOpen(false);
    setForceOpen === null || setForceOpen === void 0 ? void 0 : setForceOpen(false);
  };
  const onChange = optionsN => {
    setOptions(optionsN);
  };
  const onValueChange = evt => {
    setQuery(evt.target.value);
  };
  const anchorButton = /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    style: width ? {
      width
    } : {},
    size: "m",
    color: "text",
    iconType: "arrowDown",
    iconSide: "right",
    onClick: onButtonClick,
    "data-test-subj": 'fieldValueSelectionBtn',
    fullWidth: fullWidth
  }, label);
  const numOfFilters = (selectedValue || []).length + (excludedValue || []).length;
  const filterButton = /*#__PURE__*/_react.default.createElement(_eui.EuiFilterButton, {
    "aria-label": _i18n.i18n.translate('xpack.exploratoryView.filterButton.label', {
      defaultMessage: 'expands filter group for {label} filter',
      values: {
        label
      }
    }),
    hasActiveFilters: numOfFilters > 0,
    iconType: "arrowDown",
    numActiveFilters: numOfFilters,
    numFilters: options.length,
    onClick: onButtonClick
  }, label);
  const applyDisabled = () => {
    const currSelected = (options !== null && options !== void 0 ? options : []).filter(opt => (opt === null || opt === void 0 ? void 0 : opt.checked) === 'on').map(({
      label: labelN
    }) => labelN);
    const currExcluded = (options !== null && options !== void 0 ? options : []).filter(opt => (opt === null || opt === void 0 ? void 0 : opt.checked) === 'off').map(({
      label: labelN
    }) => labelN);
    const hasFilterSelected = (selectedValue !== null && selectedValue !== void 0 ? selectedValue : []).length > 0 || (excludedValue !== null && excludedValue !== void 0 ? excludedValue : []).length > 0;
    return (0, _lodash.isEqual)(selectedValue !== null && selectedValue !== void 0 ? selectedValue : [], currSelected) && (0, _lodash.isEqual)(excludedValue !== null && excludedValue !== void 0 ? excludedValue : [], currExcluded) && !(isLogicalAND !== useLogicalAND && hasFilterSelected);
  };
  return /*#__PURE__*/_react.default.createElement(Wrapper, null, /*#__PURE__*/_react.default.createElement(_eui.EuiPopover, {
    id: "popover",
    panelPaddingSize: "none",
    button: button || (asFilterButton ? filterButton : anchorButton),
    isOpen: isPopoverOpen || forceOpen,
    closePopover: closePopover,
    anchorPosition: anchorPosition,
    style: {
      width: '100%'
    }
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiSelectable, {
    searchable: true,
    singleSelection: singleSelection,
    searchProps: {
      placeholder: _i18n.i18n.translate('xpack.exploratoryView.fieldValueSelection.placeholder', {
        defaultMessage: 'Filter {label}',
        values: {
          label
        }
      }),
      compressed,
      onInput: onValueChange,
      'data-test-subj': 'suggestionInputField'
    },
    listProps: {
      onFocusBadge: false
    },
    options: options,
    onChange: onChange,
    allowExclusions: allowExclusions,
    isLoading: loading && !query && options.length === 0
  }, (list, search) => /*#__PURE__*/_react.default.createElement("div", {
    style: {
      width: 240
    }
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiPopoverTitle, {
    paddingSize: "s"
  }, search), list, loading && query && /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    className: "eui-textCenter",
    color: "subdued"
  }, _i18n.i18n.translate('xpack.exploratoryView.fieldValueSelection.loading', {
    defaultMessage: 'Loading'
  }), ' ', /*#__PURE__*/_react.default.createElement(_eui.EuiLoadingSpinner, {
    size: "m"
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiPopoverFooter, {
    paddingSize: "s"
  }, showLogicalConditionSwitch && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "xs"
  }), /*#__PURE__*/_react.default.createElement("div", {
    css: {
      display: 'flex',
      justifyContent: 'flex-end'
    }
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiSwitch, {
    css: {
      flexDirection: 'row-reverse',
      gap: euiTheme.size.s,
      color: euiTheme.colors.subduedText
    },
    label: _i18n.i18n.translate('xpack.exploratoryView.fieldValueSelection.logicalAnd', {
      defaultMessage: 'Use logical AND'
    }),
    "data-test-subj": "tagsLogicalOperatorSwitch",
    checked: Boolean(isLogicalAND),
    compressed: true,
    onChange: e => {
      setIsLogicalAND(e.target.checked);
    }
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "m"
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    "data-test-subj": "o11yFieldValueSelectionApplyButton",
    "aria-label": _i18n.i18n.translate('xpack.exploratoryView.fieldValueSelection.apply.label', {
      defaultMessage: 'Apply the selected filters for {label}',
      values: {
        label
      }
    }),
    fill: true,
    fullWidth: true,
    size: "s",
    isDisabled: applyDisabled(),
    onClick: () => {
      const selectedValuesN = options.filter(opt => (opt === null || opt === void 0 ? void 0 : opt.checked) === 'on');
      const excludedValuesN = options.filter(opt => (opt === null || opt === void 0 ? void 0 : opt.checked) === 'off');
      if (showLogicalConditionSwitch) {
        onSelectionChange((0, _lodash.map)(selectedValuesN, 'label'), (0, _lodash.map)(excludedValuesN, 'label'), isLogicalAND);
      } else {
        onSelectionChange((0, _lodash.map)(selectedValuesN, 'label'), (0, _lodash.map)(excludedValuesN, 'label'));
      }
      setIsPopoverOpen(false);
      setForceOpen === null || setForceOpen === void 0 ? void 0 : setForceOpen(false);
    }
  }, _i18n.i18n.translate('xpack.exploratoryView.fieldValueSelection.apply', {
    defaultMessage: 'Apply'
  })))))));
}

// eslint-disable-next-line import/no-default-export
var _default = FieldValueSelection;
exports.default = _default;
const Wrapper = _styledComponents.default.div`
  &&& {
    div.euiPopover__anchor {
      width: 100%;
      .euiButton {
        width: 100%;
      }
    }
  }
`;