import { css, cx } from '@emotion/css';
import { useStyles2, useTheme2, Button, IconButton, Icon } from '@grafana/ui';
import { t } from '@grafana/i18n';
import React, { memo, useState, useRef, useEffect } from 'react';
import { useMeasure } from 'react-use';
import { AdHocFilterPill } from './AdHocFilterPill.js';
import { AdHocFiltersAlwaysWipCombobox } from './AdHocFiltersAlwaysWipCombobox.js';
import { GroupByPill } from './GroupByPill.js';
import { isGroupByFilter } from '../AdHocFiltersVariable.js';
import { AdHocGroupByRecommendationsRenderer } from '../AdHocFiltersRecommendations.js';

const MAX_VISIBLE_FILTERS_DEFAULT = 4;
const MAX_VISIBLE_FILTERS_WITH_GROUP_BY = 2;
const MAX_VISIBLE_GROUP_BY = 2;
const AdHocFiltersComboboxRenderer = memo(function AdHocFiltersComboboxRenderer2({ controller }) {
  var _a;
  const { originFilters, filters, readOnly, collapsible, valueRecommendations, enableGroupBy, groupByRestorable } = controller.useState();
  const styles = useStyles2(getStyles);
  const theme = useTheme2();
  const [collapsed, setCollapsed] = useState(true);
  const [wrapperRef, { height: wrapperHeight }] = useMeasure();
  const clearAll = () => {
    var _a2;
    (_a2 = controller.clearAll) == null ? void 0 : _a2.call(controller);
  };
  const focusOnWipInputRef = useRef();
  const focusOnGroupByWipInputRef = useRef();
  const singleLineThreshold = theme.spacing.gridSize * 5;
  const isMultiLine = collapsible && wrapperHeight > singleLineThreshold;
  const handleCollapseToggle = (event) => {
    event.stopPropagation();
    if (collapsible) {
      setCollapsed(true);
    }
  };
  const handleExpand = () => {
    if (collapsible && collapsed) {
      setCollapsed(false);
    }
  };
  const visibleOriginFilters = (_a = originFilters == null ? void 0 : originFilters.filter((f) => f.origin && !f.hidden && !f.dismissedGroupBy)) != null ? _a : [];
  const visibleFilters = filters.filter((f) => !f.hidden);
  const allFilters = [...visibleOriginFilters, ...visibleFilters];
  const totalFiltersCount = allFilters.length;
  const adhocFilters = allFilters.filter((f) => !isGroupByFilter(f));
  const groupByFilters = allFilters.filter(isGroupByFilter);
  const shouldCollapse = collapsible && collapsed && totalFiltersCount > 0;
  const maxVisibleAdhocFilters = enableGroupBy ? MAX_VISIBLE_FILTERS_WITH_GROUP_BY : MAX_VISIBLE_FILTERS_DEFAULT;
  const adhocFiltersToRender = shouldCollapse ? adhocFilters.slice(0, maxVisibleAdhocFilters) : adhocFilters;
  const adhocHiddenCount = shouldCollapse ? Math.max(0, adhocFilters.length - maxVisibleAdhocFilters) : 0;
  const groupByFiltersToRender = shouldCollapse ? groupByFilters.slice(0, MAX_VISIBLE_GROUP_BY) : groupByFilters;
  const groupByHiddenCount = shouldCollapse ? Math.max(0, groupByFilters.length - MAX_VISIBLE_GROUP_BY) : 0;
  const variableControlId = controller.getControlId();
  useEffect(() => {
    if (collapsible && totalFiltersCount === 0 && collapsed) {
      setCollapsed(false);
    }
  }, [collapsible, totalFiltersCount, collapsed]);
  const showCollapseButton = collapsible && isMultiLine && !collapsed;
  const showExpandButton = shouldCollapse && (adhocHiddenCount > 0 || groupByHiddenCount > 0);
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      ref: wrapperRef,
      className: cx(styles.comboboxWrapper, {
        [styles.comboboxFocusOutline]: !readOnly,
        [styles.collapsed]: shouldCollapse
      })
    },
    !readOnly && valueRecommendations && /* @__PURE__ */ React.createElement(valueRecommendations.Component, { model: valueRecommendations }),
    adhocFiltersToRender.length > 0 && // if there are filters already selected, this makes sure
    // that the input is announced before focussing on the pills
    /* @__PURE__ */ React.createElement(
      "span",
      {
        tabIndex: 0,
        "aria-labelledby": variableControlId,
        className: styles.screenReaderOnlyLabel,
        "data-testid": "AdHocFilter-label-announcer"
      }
    ),
    adhocFiltersToRender.map((filter, index) => /* @__PURE__ */ React.createElement(
      AdHocFilterPill,
      {
        key: `${filter.origin ? "origin-" : ""}${index}-${filter.key}`,
        filter,
        controller,
        readOnly: readOnly || filter.readOnly,
        focusOnWipInputRef: focusOnWipInputRef.current
      }
    )),
    shouldCollapse && adhocHiddenCount > 0 && /* @__PURE__ */ React.createElement(
      Button,
      {
        className: styles.moreIndicator,
        fill: "text",
        size: "sm",
        "aria-label": t(
          "grafana-scenes.variables.adhoc-filters-combobox-renderer.show-more-filters",
          "Show {{count}} more filters",
          { count: adhocHiddenCount }
        ),
        onClick: (e) => {
          e.stopPropagation();
          handleExpand();
          setTimeout(() => {
            var _a2;
            return (_a2 = focusOnWipInputRef.current) == null ? void 0 : _a2.call(focusOnWipInputRef);
          });
        }
      },
      "+",
      adhocHiddenCount
    ),
    !readOnly && /* @__PURE__ */ React.createElement(AdHocFiltersAlwaysWipCombobox, { ref: focusOnWipInputRef, controller, onInputClick: handleExpand }),
    enableGroupBy && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: styles.sectionDivider }), /* @__PURE__ */ React.createElement("span", { className: styles.groupByLabel }, t("grafana-scenes.variables.adhoc-filters-combobox-renderer.group-by-label", "Group by:")), !readOnly && valueRecommendations && /* @__PURE__ */ React.createElement(AdHocGroupByRecommendationsRenderer, { model: valueRecommendations }), groupByFiltersToRender.map((filter, index) => /* @__PURE__ */ React.createElement(
      GroupByPill,
      {
        key: `groupby-${index}-${filter.key}`,
        filter,
        controller,
        readOnly: readOnly || filter.readOnly,
        focusOnWipInputRef: focusOnGroupByWipInputRef.current
      }
    )), shouldCollapse && groupByHiddenCount > 0 && /* @__PURE__ */ React.createElement(
      Button,
      {
        className: styles.moreIndicator,
        fill: "text",
        size: "sm",
        "aria-label": t(
          "grafana-scenes.variables.adhoc-filters-combobox-renderer.show-more-group-by",
          "Show {{count}} more group by",
          { count: groupByHiddenCount }
        ),
        onClick: (e) => {
          e.stopPropagation();
          handleExpand();
          setTimeout(() => {
            var _a2;
            return (_a2 = focusOnGroupByWipInputRef.current) == null ? void 0 : _a2.call(focusOnGroupByWipInputRef);
          });
        }
      },
      "+",
      groupByHiddenCount
    ), !readOnly && /* @__PURE__ */ React.createElement(
      AdHocFiltersAlwaysWipCombobox,
      {
        ref: focusOnGroupByWipInputRef,
        controller,
        onInputClick: handleExpand,
        isGroupBy: true
      }
    ), groupByRestorable && /* @__PURE__ */ React.createElement(
      IconButton,
      {
        name: "history",
        size: "md",
        className: styles.controlButton,
        tooltip: t(
          "grafana-scenes.variables.adhoc-filters-combobox-renderer.restore-default-group-by",
          "Restore groupby set by this dashboard."
        ),
        onClick: () => {
          var _a2;
          return (_a2 = controller.restoreOriginalGroupBy) == null ? void 0 : _a2.call(controller);
        }
      }
    )),
    (showCollapseButton || showExpandButton || !readOnly) && /* @__PURE__ */ React.createElement("div", { className: styles.rightControls }, /* @__PURE__ */ React.createElement("div", { className: styles.sectionDivider }), showCollapseButton && /* @__PURE__ */ React.createElement(
      Button,
      {
        className: styles.collapseButton,
        fill: "text",
        size: "sm",
        onClick: handleCollapseToggle,
        "aria-label": t(
          "grafana-scenes.variables.adhoc-filters-combobox-renderer.collapse-filters",
          "Collapse filters"
        ),
        "aria-expanded": !collapsed
      },
      t("grafana-scenes.variables.adhoc-filters-combobox-renderer.collapse", "Collapse"),
      /* @__PURE__ */ React.createElement(Icon, { name: "angle-up", size: "md" })
    ), showExpandButton && /* @__PURE__ */ React.createElement(
      IconButton,
      {
        name: "angle-down",
        size: "md",
        className: styles.dropdownIndicator,
        tooltip: t("grafana-scenes.variables.adhoc-filters-combobox-renderer.expand-filters", "Expand filters"),
        onClick: (e) => {
          e.stopPropagation();
          handleExpand();
        }
      }
    ), !readOnly && /* @__PURE__ */ React.createElement(
      IconButton,
      {
        name: "times",
        size: "md",
        className: styles.controlButton,
        tooltip: t("grafana-scenes.variables.adhoc-filters-combobox-renderer.clear-all", "Clear all"),
        onClick: clearAll
      }
    ))
  );
});
const getStyles = (theme) => ({
  comboboxWrapper: css({
    display: "flex",
    flexWrap: "wrap",
    alignItems: "center",
    columnGap: theme.spacing(1),
    rowGap: theme.spacing(0.5),
    minHeight: theme.spacing(4),
    backgroundColor: theme.components.input.background,
    border: `1px solid ${theme.colors.border.strong}`,
    borderRadius: theme.shape.radius.default,
    paddingInline: theme.spacing(1),
    paddingBlock: theme.spacing(0.5),
    flexGrow: 1,
    width: "100%"
  }),
  comboboxFocusOutline: css({
    "&:focus-within": {
      outline: "2px dotted transparent",
      outlineOffset: "2px",
      boxShadow: `0 0 0 2px ${theme.colors.background.canvas}, 0 0 0px 4px ${theme.colors.primary.main}`,
      transitionTimingFunction: `cubic-bezier(0.19, 1, 0.22, 1)`,
      transitionDuration: "0.2s",
      transitionProperty: "outline, outline-offset, box-shadow",
      zIndex: 2
    }
  }),
  collapsed: css({
    flexWrap: "nowrap",
    overflow: "hidden"
  }),
  rightControls: css({
    display: "flex",
    alignItems: "center",
    marginLeft: "auto",
    flexShrink: 0,
    gap: theme.spacing(1.5)
  }),
  moreIndicator: css({
    color: theme.colors.text.primary,
    background: theme.colors.action.selected,
    height: "auto",
    lineHeight: "normal",
    alignSelf: "stretch",
    "&:hover": {
      background: theme.colors.action.hover
    }
  }),
  dropdownIndicator: css({
    color: theme.colors.text.secondary,
    flexShrink: 0
  }),
  collapseButton: css({
    color: theme.colors.text.secondary,
    padding: 0,
    height: "auto",
    lineHeight: "normal",
    "&:hover": {
      background: "transparent",
      color: theme.colors.text.primary
    }
  }),
  sectionDivider: css({
    width: "1px",
    alignSelf: "stretch",
    backgroundColor: theme.colors.border.weak,
    flexShrink: 0
  }),
  groupByLabel: css({
    ...theme.typography.bodySmall,
    fontWeight: theme.typography.fontWeightBold,
    color: theme.colors.text.primary,
    whiteSpace: "nowrap"
  }),
  controlButton: css({
    color: theme.colors.text.secondary,
    "&:hover": {
      color: theme.colors.text.primary
    }
  }),
  screenReaderOnlyLabel: css({
    position: "absolute",
    width: "1px",
    height: "1px",
    padding: 0,
    margin: "-1px",
    overflow: "hidden",
    clip: "rect(0, 0, 0, 0)",
    whiteSpace: "nowrap",
    border: 0
  })
});

export { AdHocFiltersComboboxRenderer };
//# sourceMappingURL=AdHocFiltersComboboxRenderer.js.map
