import { useEnvironment, EntityAccessor, Entity } from "@contember/binding";
import { emptyArray } from "@contember/react-utils";
import { Dropdown, AnchorButton, FieldContainer, Checkbox, ButtonGroup } from "@contember/ui";
import { useCallback, useEffect, useMemo } from "react";
import { renderByJoining } from "./renderByJoining.js";
import { jsxDEV } from "react/jsx-dev-runtime";
import { useRedirect } from "../../../../routing/binding/useRedirect.js";
import { RoutingLink } from "../../../../routing/RoutingLink.js";
var _jsxFileName = "/__w/interface/interface/packages/admin/src/components/bindingFacade/environment/DimensionsSwitcher/DimensionsRenderer.tsx";
function DimensionsRenderer(props) {
  const environment = useEnvironment();
  const redirect = useRedirect();
  const renderSelected = useCallback((selectedDimensions2) => {
    const renderer = props.renderSelected || renderByJoining;
    return renderer(selectedDimensions2);
  }, [props.renderSelected]);
  const renderContent = (dimensionData, selectedDimensions2) => {
    const canSelectJustOne = props.minItems === 1 && props.maxItems === 1;
    const selectedDimensionsCount = selectedDimensions2.length;
    const canSelectAnother = selectedDimensionsCount < props.maxItems;
    const canSelectLess = selectedDimensionsCount > props.minItems;
    const getRequestChangeCallback = (dimension) => (reqState) => {
      if (reqState === null) {
        throw "Cannot switch dimension of unmatched request";
      }
      let updatedDimensions;
      if (!dimension.isSelected && !canSelectAnother) {
        updatedDimensions = [...selectedDimensions2.slice(1), dimension];
      } else if (dimension.isSelected && !canSelectLess) {
        updatedDimensions = selectedDimensions2;
      } else {
        updatedDimensions = dimensionData.filter((item) => {
          if (item.slug === dimension.slug) {
            return !item.isSelected;
          }
          return item.isSelected;
        });
      }
      return {
        ...reqState,
        dimensions: {
          ...reqState.dimensions || {},
          [props.dimension]: getUniqueDimensions(updatedDimensions.map((item) => item.slug).slice(0, props.maxItems))
        }
      };
    };
    const renderedDimensions = dimensionData.map((dimension) => {
      if (canSelectJustOne) {
        return /* @__PURE__ */ jsxDEV(RoutingLink, {
          to: getRequestChangeCallback(dimension),
          Component: ({
            href,
            onClick
          }) => /* @__PURE__ */ jsxDEV(AnchorButton, {
            href,
            flow: "block",
            distinction: "seamless",
            active: dimension.isSelected,
            onClick,
            children: dimension.label
          }, void 0, false, {
            fileName: _jsxFileName,
            lineNumber: 79,
            columnNumber: 8
          }, this)
        }, dimension.slug, false, {
          fileName: _jsxFileName,
          lineNumber: 75,
          columnNumber: 6
        }, this);
      } else {
        return /* @__PURE__ */ jsxDEV(FieldContainer, {
          label: dimension.label,
          labelPosition: "labelInlineRight",
          children: /* @__PURE__ */ jsxDEV(Checkbox, {
            value: dimension.isSelected,
            disabled: dimension.isSelected && !canSelectLess,
            onChange: () => redirect(getRequestChangeCallback(dimension))
          }, dimension.slug, false, {
            fileName: _jsxFileName,
            lineNumber: 98,
            columnNumber: 7
          }, this)
        }, dimension.slug, false, {
          fileName: _jsxFileName,
          lineNumber: 93,
          columnNumber: 6
        }, this);
      }
    });
    if (canSelectJustOne) {
      return /* @__PURE__ */ jsxDEV(ButtonGroup, {
        orientation: "vertical",
        children: renderedDimensions
      }, void 0, false, {
        fileName: _jsxFileName,
        lineNumber: 110,
        columnNumber: 11
      }, this);
    }
    return /* @__PURE__ */ jsxDEV("div", {
      style: {
        display: "flex",
        flexDirection: "column",
        gap: "0.25em",
        padding: "0.75em"
      },
      children: renderedDimensions
    }, "multipleDimensions", false, {
      fileName: _jsxFileName,
      lineNumber: 114,
      columnNumber: 4
    }, this);
  };
  const getNormalizedData = (currentDimensions, accessor) => {
    const entities = Array.from(accessor);
    const normalized = [];
    for (const entity of entities) {
      if (!(entity instanceof EntityAccessor)) {
        continue;
      }
      const slugField = entity.getField(props.slugField);
      if (typeof slugField.value === "string") {
        const slugValue = slugField.value;
        normalized.push({
          slug: slugValue,
          isSelected: currentDimensions.indexOf(slugValue) !== -1,
          label: /* @__PURE__ */ jsxDEV(Entity, {
            accessor: entity,
            children: props.labelFactory
          }, void 0, false, {
            fileName: _jsxFileName,
            lineNumber: 137,
            columnNumber: 13
          }, this)
        });
      }
    }
    return normalized;
  };
  const getUniqueDimensions = (selectedDimensions2) => {
    return selectedDimensions2.filter((item, i, array) => array.indexOf(item) === i);
  };
  const uniqueDimensions = getUniqueDimensions(environment.getDimensionOrElse(props.dimension, []));
  const normalizedData = getNormalizedData(uniqueDimensions, props.accessor);
  const selectedDimensions = normalizedData ? uniqueDimensions.filter((slug) => normalizedData.find((item) => item.slug === slug) !== void 0).map((dimension) => normalizedData.find((item) => item.slug === dimension)).filter((item) => !!item && item.isSelected) : emptyArray;
  useEffect(() => {
    const redirectTarget = selectedDimensions.length === 0 ? normalizedData || [] : selectedDimensions;
    if (normalizedData !== void 0 && selectedDimensions.length === 0 && redirectTarget.length > 0) {
      redirect((requestState) => {
        return {
          ...requestState,
          dimensions: {
            ...requestState?.dimensions ?? {},
            [props.dimension]: getUniqueDimensions(redirectTarget.map((item) => item.slug).slice(0, props.maxItems))
          }
        };
      });
    }
  }, [normalizedData, props.dimension, props.maxItems, redirect, selectedDimensions]);
  const buttonProps = useMemo(() => ({
    size: "small",
    ...props.buttonProps,
    children: renderSelected(selectedDimensions)
  }), [props.buttonProps, renderSelected, selectedDimensions]);
  if (normalizedData.length === 0) {
    return null;
  }
  if (normalizedData.length === 1) {
    return /* @__PURE__ */ jsxDEV("div", {
      className: "dimensionsSwitcher",
      children: /* @__PURE__ */ jsxDEV("div", {
        className: "dimensionsSwitcher-staticSelected",
        children: renderSelected(selectedDimensions)
      }, void 0, false, {
        fileName: _jsxFileName,
        lineNumber: 189,
        columnNumber: 5
      }, this)
    }, void 0, false, {
      fileName: _jsxFileName,
      lineNumber: 188,
      columnNumber: 4
    }, this);
  }
  return /* @__PURE__ */ jsxDEV(Dropdown, {
    buttonProps,
    children: renderContent(normalizedData, selectedDimensions)
  }, void 0, false, {
    fileName: _jsxFileName,
    lineNumber: 195,
    columnNumber: 3
  }, this);
}
export {
  DimensionsRenderer
};
//# sourceMappingURL=DimensionsRenderer.js.map
