import _Select from "@mui/material/Select";
import _MenuItem from "@mui/material/MenuItem";
import _ListItemSecondaryAction from "@mui/material/ListItemSecondaryAction";
import _Checkbox from "@mui/material/Checkbox";
import _ListSubheader from "@mui/material/ListSubheader";
import _Chip from "@mui/material/Chip";
import _Box from "@mui/material/Box";
/*!
 * 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.
 */

import styled from "@emotion/styled";
import { memo, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { Field } from "./Field.js";
import { CheckIcon, CloseCircleFilledIcon } from "./icons.generated/index.js";
import { ComponentControlledState, getControlState, useInputValues } from "./inputUtils.js";
import { useOdysseyDesignTokens } from "./OdysseyDesignTokensContext.js";
import { normalizedKey } from "./useNormalizedKey.js";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
const SelectContainer = styled.div`
  position: relative;
  width: 100%;
  display: flex;
`;
const ChipsPositioningContainer = styled("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 = styled(CloseCircleFilledIcon, {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  fontSize: "1em",
  marginBlockEnd: "-1px",
  marginInlineEnd: `-${odysseyDesignTokens.Spacing1}`,
  marginInlineStart: odysseyDesignTokens.Spacing2
}));
const ChipsInnerContainer = styled(_Box, {
  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
} = 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 = useRef(null);
  const hasMultipleChoices = useMemo(() => hasMultipleChoicesProp === undefined ? isMultiSelect : hasMultipleChoicesProp, [hasMultipleChoicesProp, isMultiSelect]);
  const controlledStateRef = useRef(getControlState({
    controlledValue: value,
    uncontrolledValue: defaultValue
  }));
  const [internalSelectedValues, setInternalSelectedValues] = useState(controlledStateRef.current === CONTROLLED ? value : defaultValue);
  const localInputRef = useRef(null);
  const odysseyDesignTokens = useOdysseyDesignTokens();
  useImperativeHandle(inputRef, () => {
    return {
      focus: () => {
        localInputRef.current?.focus();
      }
    };
  }, []);
  useEffect(() => {
    if (controlledStateRef.current === CONTROLLED) {
      setInternalSelectedValues(value);
    }
  }, [value]);
  const inputValues = useInputValues({
    defaultValue,
    value,
    controlState: controlledStateRef.current
  });
  const onChange = 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] = 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 = 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 = useCallback(({
    isInteractive,
    isReadOnly
  }) => {
    const stopPropagation = event => event.stopPropagation();
    const hasNonInteractiveIcon = !isInteractive && !isReadOnly && controlledStateRef.current === CONTROLLED && hasMultipleChoices;
    return Array.isArray(internalSelectedValues) && _jsx(ChipsInnerContainer, {
      isInteractive: isInteractive,
      isReadOnly: isReadOnly,
      odysseyDesignTokens: odysseyDesignTokens,
      children: internalSelectedValues.map(item => item?.length > 0 && _jsx(_Chip, {
        deleteIcon: _jsx(CloseCircleFilledIcon, {
          onMouseDown: stopPropagation,
          sx: {
            pointerEvents: "auto"
          }
        }),
        label: _jsxs(_Fragment, {
          children: [normalizedOptionsMap.get(item)?.text, hasNonInteractiveIcon && _jsx(NonInteractiveIcon, {
            odysseyDesignTokens: odysseyDesignTokens
          })]
        }),
        onDelete: isInteractive && controlledStateRef.current === CONTROLLED ? () => removeSelectedValue(item) : undefined,
        tabIndex: -1
      }, item))
    });
  }, [controlledStateRef, hasMultipleChoices, internalSelectedValues, odysseyDesignTokens, removeSelectedValue, normalizedOptionsMap]);
  const renderedOptions = useMemo(() => normalizedOptions.map((option, index) => {
    if (option.type === "heading") {
      return _jsxs(_ListSubheader, {
        children: [" ", option.text, " "]
      }, option.text);
    }
    const isSelected = hasMultipleChoices ? internalSelectedValues?.includes(option.value) : internalSelectedValues === option.value;
    return _jsxs(_MenuItem, {
      "data-empty": !option.text,
      lang: option.lang,
      selected: isSelected,
      value: option.value,
      children: [hasMultipleChoices && _jsx(_Checkbox, {
        checked: isSelected
      }), option.text, !hasMultipleChoices && internalSelectedValues === option.value && _jsx(_ListItemSecondaryAction, {
        children: _jsx(CheckIcon, {})
      })]
    }, normalizedKey(option.text, index.toString()));
  }), [hasMultipleChoices, normalizedOptions, internalSelectedValues]);
  const renderValue = useCallback(value => Array.isArray(value) && _jsx(Chips, {
    isInteractive: false
  }), [Chips]);
  const renderFieldComponent = useCallback(({
    ariaDescribedBy,
    errorMessageElementId,
    id,
    labelElementId
  }) => _jsxs(SelectContainer, {
    children: [_jsx(_Select, {
      ...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 && _jsx(_Fragment, {
      children: _jsx(ChipsPositioningContainer, {
        odysseyDesignTokens: odysseyDesignTokens,
        children: _jsx(Chips, {
          isInteractive: !isReadOnly,
          isReadOnly: isReadOnly
        })
      })
    })]
  }), [Chips, inputValues, hasMultipleChoices, isDisabled, isReadOnly, nameOverride, odysseyDesignTokens, onBlur, onChange, onFocus, renderedOptions, renderValue, testId, translate]);
  return _jsx(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 = memo(Select);
MemoizedSelect.displayName = "Select";
export { MemoizedSelect as Select };
//# sourceMappingURL=Select.js.map