"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { cnb } from "cnbuilder";
import { useCallback, useRef, useState } from "react";
import { IconRotator } from "../icon/IconRotator.js";
import { getIcon } from "../icon/config.js";
import { KeyboardMovementProvider } from "../movement/useKeyboardMovementProvider.js";
import { useEnsuredId } from "../useEnsuredId.js";
import { useEnsuredRef } from "../useEnsuredRef.js";
import { Listbox } from "./Listbox.js";
import { SelectedOption } from "./SelectedOption.js";
import { TextFieldContainer } from "./TextFieldContainer.js";
import { getFormConfig } from "./formConfig.js";
import { label as labelStyles } from "./labelStyles.js";
import { select } from "./selectStyles.js";
import { extractOptionsFromChildren } from "./selectUtils.js";
import { textField } from "./textFieldStyles.js";
import { useFormReset } from "./useFormReset.js";
import { useSelectCombobox } from "./useSelectCombobox.js";
import { triggerManualChangeEvent } from "./utils.js";
const EMPTY_STRING = "";
const noop = ()=>{
// do nothing
};
/**
 * @since 6.5.0
 */ const defaultGetSelectedOptionChildren = (options)=>{
    const { children, option, placeholder } = options;
    return children ?? (option?.children || placeholder);
};
/**
 * **Client Component**
 *
 * @example Simple Example
 * ```tsx
 * import { Option } from "@react-md/core/form/Option";
 * import { Select } from "@react-md/core/form/Select";
 * import { useState, type ReactElement } from "react";
 *
 * function Example(): ReactElement {
 *   const [value, setValue] = useState("");
 *
 *   return (
 *     <Select
 *       label="Select"
 *       value={value}
 *       onChange={(event) => setValue(event.currentTarget.value)}
 *       placeholder="Select a value"
 *     >
 *       <Option value="a">Option 1</Option>
 *       <Option value="b">Option 2</Option>
 *       <Option value="c">Option 3</Option>
 *       <Option value="d">Option 4</Option>
 *     </Select>
 *   );
 * }
 * ```
 *
 * @see {@link https://react-md.dev/components/select | Select Demos}
 * @since 6.0.0 Rewritten with a new API.
 */ export function Select(props) {
    const { id, form, autoCompleteValue, autoComplete = autoCompleteValue, name = autoCompleteValue, className, onClick, onFocus, onKeyDown, inputRef: propInputRef, inputProps, containerRef, placeholder, menuProps = {}, label, labelProps = {}, selectedOptionProps, getSelectedOptionChildren = defaultGetSelectedOptionChildren, icon: propIcon, value, defaultValue, theme: propTheme, onChange = noop, rightAddon: propRightAddon, active = false, required, selectedIconAfter = false, disableOptionAddon = false, disableSelectedIcon = false, children, ...remaining } = props;
    const { dense, error, disabled } = props;
    const comboboxId = useEnsuredId(id, "select");
    const inputId = useEnsuredId(inputProps?.id, "select-value");
    const selectLabelId = useEnsuredId(labelProps.id, "select-label");
    const labelId = label ? selectLabelId : undefined;
    const [localValue, setLocalValue] = useState(()=>{
        if (typeof defaultValue !== "undefined") {
            return defaultValue;
        }
        return typeof value !== "undefined" ? value : EMPTY_STRING;
    });
    const currentValue = typeof value === "undefined" ? localValue : value;
    const initialValue = useRef(currentValue);
    const { options, currentOption } = extractOptionsFromChildren(children, currentValue);
    const { visible, comboboxProps, movementContext, getMenuProps } = useSelectCombobox({
        form,
        value: currentValue,
        values: options,
        onClick,
        onFocus,
        onKeyDown,
        disabled,
        popupId: menuProps.id,
        popupRef: menuProps.ref,
        comboboxId,
        comboboxRef: containerRef
    });
    const [inputRef, inputRefCallback] = useEnsuredRef(propInputRef);
    useFormReset({
        form,
        elementRef: inputRef,
        defaultValue: initialValue.current
    });
    const icon = getIcon("dropdown", propIcon);
    const theme = getFormConfig("theme", propTheme);
    let rightAddon = propRightAddon;
    if (typeof rightAddon === "undefined" && icon) {
        rightAddon = /*#__PURE__*/ _jsx(IconRotator, {
            rotated: visible,
            children: icon
        });
    }
    const { ref: listboxRef, ...listboxProps } = getMenuProps(menuProps);
    let listboxLabelledBy = menuProps["aria-labelledby"];
    const listboxLabel = menuProps["aria-label"];
    if (!listboxLabel && !listboxLabelledBy) {
        listboxLabelledBy = labelId || comboboxId;
    }
    return /*#__PURE__*/ _jsxs(KeyboardMovementProvider, {
        value: movementContext,
        children: [
            /*#__PURE__*/ _jsxs(TextFieldContainer, {
                "aria-labelledby": labelId,
                ...remaining,
                ...comboboxProps,
                label: !!label,
                theme: theme,
                active: active || visible,
                className: cnb("rmd-select-container", className),
                rightAddon: rightAddon,
                children: [
                    /*#__PURE__*/ _jsx(SelectedOption, {
                        option: currentOption,
                        disableAddon: disableOptionAddon,
                        ...selectedOptionProps,
                        children: getSelectedOptionChildren({
                            value: currentValue,
                            option: currentOption,
                            placeholder,
                            children: selectedOptionProps?.children
                        })
                    }),
                    /*#__PURE__*/ _jsx("input", {
                        "aria-hidden": true,
                        id: inputId,
                        ref: inputRefCallback,
                        type: "text",
                        autoComplete: autoComplete,
                        name: name,
                        tabIndex: -1,
                        disabled: disabled,
                        required: required,
                        placeholder: " ",
                        ...inputProps,
                        value: value,
                        defaultValue: defaultValue,
                        className: cnb(select({
                            theme
                        }), textField()),
                        onChange: (event)=>{
                            onChange(event);
                            if (typeof value !== "undefined") {
                                return;
                            }
                            const nextValue = event.currentTarget.value;
                            const nextOption = options.find((option)=>option === nextValue);
                            setLocalValue(nextOption ?? initialValue.current);
                        }
                    }),
                    label && /*#__PURE__*/ _jsx("span", {
                        ...labelProps,
                        id: labelId,
                        className: labelStyles({
                            dense,
                            error,
                            disabled,
                            active: active || visible,
                            floating: true,
                            floatingActive: !!placeholder || !!currentOption,
                            className: labelProps.className
                        }),
                        children: label
                    })
                ]
            }),
            /*#__PURE__*/ _jsx(Listbox, {
                ...listboxProps,
                "aria-label": listboxLabel,
                "aria-labelledby": listboxLabelledBy,
                nodeRef: listboxRef,
                value: currentValue,
                setValue: useCallback((option)=>{
                    triggerManualChangeEvent(inputRef.current, option);
                }, [
                    inputRef
                ]),
                selectedIconAfter: selectedIconAfter,
                disableSelectedIcon: disableSelectedIcon,
                children: children
            })
        ]
    });
}

//# sourceMappingURL=Select.js.map