import { jsx, jsxs } from 'react/jsx-runtime';
import { css } from '@emotion/css';
import { useMemo, useState, useRef, useCallback } from 'react';
import { selectors } from '@grafana/e2e-selectors';
import { t, Trans } from '@grafana/i18n';
import { useTheme2, useStyles2 } from '../../../../themes/ThemeContext.mjs';
import { Button } from '../../../Button/Button.mjs';
import { ClickOutsideWrapper } from '../../../ClickOutsideWrapper/ClickOutsideWrapper.mjs';
import { ButtonSelect } from '../../../Dropdown/ButtonSelect.mjs';
import { FilterInput } from '../../../FilterInput/FilterInput.mjs';
import { Label } from '../../../Forms/Label.mjs';
import { Stack } from '../../../Layout/Stack/Stack.mjs';
import { getDisplayName } from '../utils.mjs';
import { FilterList } from './FilterList.mjs';
import { calculateUniqueFieldValues, valuesToOptions, getFilteredOptions } from './utils.mjs';

"use strict";
const operatorSelectableValues = {
  Contains: { label: "Contains", value: "Contains", description: "Contains" },
  "=": { label: "=", value: "=", description: "Equals" },
  "!=": { label: "!=", value: "!=", description: "Not equals" },
  ">": { label: ">", value: ">", description: "Greater" },
  ">=": { label: ">=", value: ">=", description: "Greater or Equal" },
  "<": { label: "<", value: "<", description: "Less" },
  "<=": { label: "<=", value: "<=", description: "Less or Equal" },
  Expression: {
    label: "Expression",
    value: "Expression",
    description: 'Bool Expression (Char $ represents the column value in the expression, e.g. "$ >= 10 && $ <= 12")'
  }
};
const OPERATORS = Object.values(operatorSelectableValues);
const FilterPopup = ({
  name,
  rows,
  filterValue,
  setFilter,
  onClose,
  field,
  searchFilter,
  setSearchFilter,
  operator,
  setOperator
}) => {
  var _a;
  const theme = useTheme2();
  const uniqueValues = useMemo(() => calculateUniqueFieldValues(rows, field), [rows, field]);
  const options = useMemo(() => valuesToOptions(uniqueValues), [uniqueValues]);
  const filteredOptions = useMemo(() => getFilteredOptions(options, filterValue), [options, filterValue]);
  const [values, setValues] = useState(filteredOptions);
  const [matchCase, setMatchCase] = useState(false);
  const containerRef = useRef(null);
  const onCancel = useCallback((event) => onClose(), [onClose]);
  const onFilter = useCallback(
    (event) => {
      if (values.length !== 0) {
        const filteredSet = new Set(values.map((item) => item.value));
        setFilter((filter) => ({
          ...filter,
          [name]: { filtered: values, filteredSet, searchFilter, operator }
        }));
      } else {
        setFilter((filter) => {
          const newFilter = { ...filter };
          delete newFilter[name];
          return newFilter;
        });
      }
      onClose();
    },
    [setFilter, values, onClose]
    // eslint-disable-line react-hooks/exhaustive-deps
  );
  const onClearFilter = useCallback(
    (event) => {
      setFilter((filter) => {
        const newFilter = { ...filter };
        delete newFilter[name];
        return newFilter;
      });
      onClose();
    },
    [setFilter, onClose]
    // eslint-disable-line react-hooks/exhaustive-deps
  );
  const filterInputPlaceholder = t("grafana-ui.table.filter-popup-input-placeholder", "Filter values");
  const clearFilterVisible = useMemo(() => filterValue !== void 0, [filterValue]);
  const styles = useStyles2(getStyles);
  return /* @__PURE__ */ jsx(ClickOutsideWrapper, { onClick: onCancel, useCapture: true, children: /* @__PURE__ */ jsx(
    "div",
    {
      className: styles.filterContainer,
      onClick: stopPropagation,
      "data-testid": selectors.components.Panels.Visualization.TableNG.Filters.Container,
      ref: containerRef,
      children: /* @__PURE__ */ jsxs(Stack, { direction: "column", children: [
        /* @__PURE__ */ jsxs(Stack, { alignItems: "center", children: [
          field && /* @__PURE__ */ jsx(Label, { className: styles.label, children: getDisplayName(field) }),
          /* @__PURE__ */ jsx(
            ButtonSelect,
            {
              variant: "canvas",
              options: OPERATORS,
              onChange: setOperator,
              value: operator,
              tooltip: operator.description,
              root: (_a = containerRef.current) != null ? _a : void 0
            }
          )
        ] }),
        /* @__PURE__ */ jsx("div", { className: styles.listDivider }),
        /* @__PURE__ */ jsxs(Stack, { gap: 1, children: [
          /* @__PURE__ */ jsx(
            FilterInput,
            {
              placeholder: filterInputPlaceholder,
              title: filterInputPlaceholder,
              onChange: setSearchFilter,
              value: searchFilter
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              tooltip: t("grafana-ui.table.filter-popup-aria-label-match-case", "Match case"),
              variant: "secondary",
              style: { color: matchCase ? theme.colors.text.link : theme.colors.text.disabled },
              onClick: () => {
                setMatchCase((s) => !s);
              },
              icon: "text-fields"
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          FilterList,
          {
            onChange: setValues,
            values,
            options,
            caseSensitive: matchCase,
            searchFilter,
            operator
          }
        ),
        /* @__PURE__ */ jsxs(Stack, { gap: 3, children: [
          /* @__PURE__ */ jsxs(Stack, { children: [
            /* @__PURE__ */ jsx(Button, { size: "sm", onClick: onFilter, children: /* @__PURE__ */ jsx(Trans, { i18nKey: "grafana-ui.table.filter-popup-apply", children: "Ok" }) }),
            /* @__PURE__ */ jsx(Button, { size: "sm", variant: "secondary", onClick: onCancel, children: /* @__PURE__ */ jsx(Trans, { i18nKey: "grafana-ui.table.filter-popup-cancel", children: "Cancel" }) })
          ] }),
          clearFilterVisible && /* @__PURE__ */ jsx(Stack, { children: /* @__PURE__ */ jsx(Button, { fill: "text", size: "sm", onClick: onClearFilter, children: /* @__PURE__ */ jsx(Trans, { i18nKey: "grafana-ui.table.filter-popup-clear", children: "Clear filter" }) }) })
        ] })
      ] })
    }
  ) });
};
const getStyles = (theme) => ({
  filterContainer: css({
    label: "filterContainer",
    width: "100%",
    minWidth: "250px",
    height: "100%",
    backgroundColor: theme.colors.background.primary,
    border: `1px solid ${theme.colors.border.weak}`,
    padding: theme.spacing(2),
    boxShadow: theme.shadows.z3,
    borderRadius: theme.shape.radius.default
  }),
  listDivider: css({
    label: "listDivider",
    width: "100%",
    borderTop: `1px solid ${theme.colors.border.medium}`
  }),
  label: css({
    marginBottom: 0
  })
});
const stopPropagation = (event) => {
  event.stopPropagation();
};

export { FilterPopup, operatorSelectableValues };
//# sourceMappingURL=FilterPopup.mjs.map
