"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOptionText = void 0;
exports.default = useSelect;
const react_1 = require("react");
const utils_1 = require("../utils");
const getOptionText = (value, options) => {
    const option = options === null || options === void 0 ? void 0 : options.find((o) => (o === null || o === void 0 ? void 0 : o.value) === value);
    return (option === null || option === void 0 ? void 0 : option.text) || value;
};
exports.getOptionText = getOptionText;
/** Handles controlled/uncontrolled value state. Supports single and multiple values. */
function useSelect(props) {
    const { defaultValue, isMultiple, onChange: onChangeProp, value: valueProp, options = [], selectedText, children, } = props;
    // Not using useControlled here, because we need custom value setter when uncontrolled
    const [stateValue, setStateValue] = (0, react_1.useState)(defaultValue);
    const isControlled = valueProp !== undefined;
    const value = isControlled ? valueProp : stateValue;
    // Iterating over the children to dynamically obtain the list of available options
    const dynamicOptions = [];
    react_1.Children.forEach(children, element => {
        if (!(0, react_1.isValidElement)(element))
            return;
        const option = element.props;
        if (option.text && option.value)
            dynamicOptions.push(option);
    });
    /** Sends a change event to the external consumer, but internall keeps the actual value as primitive or array. */
    const onChange = (0, utils_1.useCallbackRef)((e) => {
        onChangeProp === null || onChangeProp === void 0 ? void 0 : onChangeProp(e);
        if (!isControlled)
            setStateValue(value => (Array.isArray(value) ? (0, utils_1.toggleItem)(value, e.target.value).sort() : e.target.value));
    });
    const valueText = isMultiple && Array.isArray(value)
        ? value[0]
            ? selectedText && value.length > 1
                ? selectedText
                : `${(0, exports.getOptionText)(value[0], [...options, ...dynamicOptions])}${value.length > 1 ? ` (+${value.length - 1})` : ''}`
            : undefined
        : (0, exports.getOptionText)(value, [...options, ...dynamicOptions]);
    return { onChange, value, valueText };
}
//# sourceMappingURL=useSelect.js.map