"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Select = void 0;
var _Select2 = _interopRequireDefault(require("@mui/material/Select"));
var _MenuItem2 = _interopRequireDefault(require("@mui/material/MenuItem"));
var _ListItemSecondaryAction2 = _interopRequireDefault(require("@mui/material/ListItemSecondaryAction"));
var _Checkbox2 = _interopRequireDefault(require("@mui/material/Checkbox"));
var _ListSubheader2 = _interopRequireDefault(require("@mui/material/ListSubheader"));
var _Chip2 = _interopRequireDefault(require("@mui/material/Chip"));
var _Box2 = _interopRequireDefault(require("@mui/material/Box"));
var _styled = _interopRequireDefault(require("@emotion/styled"));
var _react = require("react");
var _Field = require("./Field.cjs");
var _index = require("./icons.generated/index.cjs");
var _inputUtils = require("./inputUtils.cjs");
var _OdysseyDesignTokensContext = require("./OdysseyDesignTokensContext.cjs");
var _useNormalizedKey = require("./useNormalizedKey.cjs");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/*!
 * Copyright (c) 2022-present, Okta, Inc. and/or its affiliates. All rights reserved.
 * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
 *
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and limitations under the License.
 */

const SelectContainer = _styled.default.div`
  position: relative;
  width: 100%;
  display: flex;
`;
const ChipsPositioningContainer = (0, _styled.default)("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => {
  return {
    alignItems: "center",
    display: "flex",
    insetBlockEnd: 0,
    insetBlockStart: 0,
    insetInlineEnd: "25px",
    insetInlineStart: "4px",
    marginInlineStart: odysseyDesignTokens.BorderWidthMain,
    opacity: 1,
    pointerEvents: "none",
    position: "absolute"
  };
});
const NonInteractiveIcon = (0, _styled.default)(_index.CloseCircleFilledIcon, {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  fontSize: "1em",
  marginBlockEnd: "-1px",
  marginInlineEnd: `-${odysseyDesignTokens.Spacing1}`,
  marginInlineStart: odysseyDesignTokens.Spacing2
}));
const ChipsInnerContainer = (0, _styled.default)(_Box2.default, {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens" && prop !== "isInteractive" && prop !== "isReadOnly"
})(({
  isInteractive,
  isReadOnly,
  odysseyDesignTokens
}) => ({
  display: "flex",
  flexWrap: "wrap",
  gap: odysseyDesignTokens.Spacing1,
  marginBlock: `-${odysseyDesignTokens.Spacing2}`,
  marginInlineEnd: odysseyDesignTokens.Spacing1,
  minHeight: odysseyDesignTokens.Spacing6,
  opacity: isInteractive || isReadOnly ? 1 : 0,
  pointerEvents: "none"
}));
const {
  CONTROLLED
} = _inputUtils.ComponentControlledState;
const Select = ({
  ariaDescribedBy,
  defaultValue,
  errorMessage,
  errorMessageList,
  hasMultipleChoices: hasMultipleChoicesProp,
  hint,
  HintLinkComponent,
  id: idOverride,
  inputRef,
  isDisabled = false,
  isFullWidth = false,
  isMultiSelect,
  isOptional = false,
  isReadOnly = false,
  label,
  name: nameOverride,
  onBlur,
  onChange: onChangeProp,
  onFocus,
  options,
  testId,
  translate,
  value
}) => {
  const selectRef = (0, _react.useRef)(null);
  const hasMultipleChoices = (0, _react.useMemo)(() => hasMultipleChoicesProp === undefined ? isMultiSelect : hasMultipleChoicesProp, [hasMultipleChoicesProp, isMultiSelect]);
  const controlledStateRef = (0, _react.useRef)((0, _inputUtils.getControlState)({
    controlledValue: value,
    uncontrolledValue: defaultValue
  }));
  const [internalSelectedValues, setInternalSelectedValues] = (0, _react.useState)(controlledStateRef.current === CONTROLLED ? value : defaultValue);
  const localInputRef = (0, _react.useRef)(null);
  const odysseyDesignTokens = (0, _OdysseyDesignTokensContext.useOdysseyDesignTokens)();
  (0, _react.useImperativeHandle)(inputRef, () => {
    return {
      focus: () => {
        localInputRef.current?.focus();
      }
    };
  }, []);
  (0, _react.useEffect)(() => {
    if (controlledStateRef.current === CONTROLLED) {
      setInternalSelectedValues(value);
    }
  }, [value]);
  const inputValues = (0, _inputUtils.useInputValues)({
    defaultValue,
    value,
    controlState: controlledStateRef.current
  });
  const onChange = (0, _react.useCallback)((event, child) => {
    if (isReadOnly) {
      event.preventDefault();
    } else {
      const {
        target: {
          value
        }
      } = event;
      if (controlledStateRef.current !== CONTROLLED) {
        setInternalSelectedValues(typeof value === "string" && hasMultipleChoices ? value.split(",") : value);
      }
      onChangeProp?.(event, child);
    }
  }, [hasMultipleChoices, onChangeProp, isReadOnly]);
  const [normalizedOptions, normalizedOptionsMap] = (0, _react.useMemo)(() => {
    const normalizedOptions = options.map(option => {
      if (typeof option === "object") {
        const value = option?.value === "" ? option.value : option.value || option.text;
        return {
          text: option.text,
          value,
          type: option.type === "heading" ? "heading" : "option",
          lang: option.language
        };
      }
      return {
        text: option,
        value: option,
        type: "option"
      };
    });
    const normalizedOptionsMap = new Map(normalizedOptions.map(option => [option.value, option]));
    return [normalizedOptions, normalizedOptionsMap];
  }, [options]);
  const removeSelectedValue = (0, _react.useCallback)(selectedValue => {
    if (Array.isArray(internalSelectedValues)) {
      const newValue = internalSelectedValues.filter(internalSelectedValue => internalSelectedValue !== selectedValue);
      const syntheticEvent = {
        target: {
          value: newValue
        }
      };
      onChange(syntheticEvent, null);
    }
  }, [internalSelectedValues, onChange]);
  const Chips = (0, _react.useCallback)(({
    isInteractive,
    isReadOnly
  }) => {
    const stopPropagation = event => event.stopPropagation();
    const hasNonInteractiveIcon = !isInteractive && !isReadOnly && controlledStateRef.current === CONTROLLED && hasMultipleChoices;
    return Array.isArray(internalSelectedValues) && (0, _jsxRuntime.jsx)(ChipsInnerContainer, {
      isInteractive: isInteractive,
      isReadOnly: isReadOnly,
      odysseyDesignTokens: odysseyDesignTokens,
      children: internalSelectedValues.map(item => item?.length > 0 && (0, _jsxRuntime.jsx)(_Chip2.default, {
        deleteIcon: (0, _jsxRuntime.jsx)(_index.CloseCircleFilledIcon, {
          onMouseDown: stopPropagation,
          sx: {
            pointerEvents: "auto"
          }
        }),
        label: (0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
          children: [normalizedOptionsMap.get(item)?.text, hasNonInteractiveIcon && (0, _jsxRuntime.jsx)(NonInteractiveIcon, {
            odysseyDesignTokens: odysseyDesignTokens
          })]
        }),
        onDelete: isInteractive && controlledStateRef.current === CONTROLLED ? () => removeSelectedValue(item) : undefined,
        tabIndex: -1
      }, item))
    });
  }, [controlledStateRef, hasMultipleChoices, internalSelectedValues, odysseyDesignTokens, removeSelectedValue, normalizedOptionsMap]);
  const renderedOptions = (0, _react.useMemo)(() => normalizedOptions.map((option, index) => {
    if (option.type === "heading") {
      return (0, _jsxRuntime.jsxs)(_ListSubheader2.default, {
        children: [" ", option.text, " "]
      }, option.text);
    }
    const isSelected = hasMultipleChoices ? internalSelectedValues?.includes(option.value) : internalSelectedValues === option.value;
    return (0, _jsxRuntime.jsxs)(_MenuItem2.default, {
      "data-empty": !option.text,
      lang: option.lang,
      selected: isSelected,
      value: option.value,
      children: [hasMultipleChoices && (0, _jsxRuntime.jsx)(_Checkbox2.default, {
        checked: isSelected
      }), option.text, !hasMultipleChoices && internalSelectedValues === option.value && (0, _jsxRuntime.jsx)(_ListItemSecondaryAction2.default, {
        children: (0, _jsxRuntime.jsx)(_index.CheckIcon, {})
      })]
    }, (0, _useNormalizedKey.normalizedKey)(option.text, index.toString()));
  }), [hasMultipleChoices, normalizedOptions, internalSelectedValues]);
  const renderValue = (0, _react.useCallback)(value => Array.isArray(value) && (0, _jsxRuntime.jsx)(Chips, {
    isInteractive: false
  }), [Chips]);
  const renderFieldComponent = (0, _react.useCallback)(({
    ariaDescribedBy,
    errorMessageElementId,
    id,
    labelElementId
  }) => (0, _jsxRuntime.jsxs)(SelectContainer, {
    children: [(0, _jsxRuntime.jsx)(_Select2.default, {
      ...inputValues,
      "aria-describedby": ariaDescribedBy,
      "aria-errormessage": errorMessageElementId,
      displayEmpty: true,
      id: id,
      inputProps: {
        "data-se": testId,
        "aria-disabled": isDisabled || isReadOnly,
        readOnly: isReadOnly
      },
      inputRef: el => {
        if (localInputRef.current !== el) {
          localInputRef.current = el;
        }
        selectRef.current = el;
      },
      labelId: labelElementId,
      MenuProps: {
        sx: {
          ".MuiPaper-root": {
            maxHeight: "50vh"
          }
        }
      },
      multiple: hasMultipleChoices,
      name: nameOverride ?? id,
      onBlur: onBlur,
      onChange: onChange,
      onFocus: onFocus,
      renderValue: hasMultipleChoices ? renderValue : undefined,
      translate: translate,
      children: renderedOptions
    }), hasMultipleChoices && (0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
      children: (0, _jsxRuntime.jsx)(ChipsPositioningContainer, {
        odysseyDesignTokens: odysseyDesignTokens,
        children: (0, _jsxRuntime.jsx)(Chips, {
          isInteractive: !isReadOnly,
          isReadOnly: isReadOnly
        })
      })
    })]
  }), [Chips, inputValues, hasMultipleChoices, isDisabled, isReadOnly, nameOverride, odysseyDesignTokens, onBlur, onChange, onFocus, renderedOptions, renderValue, testId, translate]);
  return (0, _jsxRuntime.jsx)(_Field.Field, {
    ariaDescribedBy: ariaDescribedBy,
    errorMessage: errorMessage,
    errorMessageList: errorMessageList,
    fieldType: "single",
    hasVisibleLabel: true,
    hint: hint,
    HintLinkComponent: HintLinkComponent,
    id: idOverride,
    isDisabled: isDisabled,
    isFullWidth: isFullWidth,
    isOptional: isOptional,
    label: label,
    renderFieldComponent: renderFieldComponent
  });
};
const MemoizedSelect = exports.Select = (0, _react.memo)(Select);
MemoizedSelect.displayName = "Select";
//# sourceMappingURL=Select.cjs.map