import { __assign, __read, __rest } from "tslib";
import React, { useEffect, useRef, useState } from "react";
import useDebounce from "../hooks/useDebounce";
import { useStateProps } from "../hooks/useStateProps";
import { useResizeObserver } from "../hooks/useResizeObserver";
import { Bracket, ControlItem, SegmentedControlBase, SegmentedControlWrapper } from "./styles";
export var SegmentedControl = function (_a) {
    var className = _a.className, options = _a.options, value = _a.value, _b = _a.size, size = _b === void 0 ? "l" : _b, onChange = _a.onChange, props = __rest(_a, ["className", "options", "value", "size", "onChange"]);
    var _c = __read(useState({}), 2), selectPosition = _c[0], setSelection = _c[1];
    var _d = __read(useStateProps(value), 2), selectedValue = _d[0], setValue = _d[1];
    var ref = useRef({});
    var segmentedControlRef = useRef(null);
    var _e = __read(useState(0), 2), segmentedControlWidth = _e[0], setSegmentedControlWidth = _e[1];
    var setSegmentedControlWidthDebounce = useDebounce(setSegmentedControlWidth, 100);
    var optionalCallback = function (entry) {
        return setSegmentedControlWidthDebounce(entry.width);
    };
    useResizeObserver(segmentedControlRef, optionalCallback);
    useEffect(function () {
        if (selectedValue && ref.current[selectedValue]) {
            var selectedOption = options.find(function (opt) { return opt.value === selectedValue; });
            if (selectedOption === null || selectedOption === void 0 ? void 0 : selectedOption.isDisabled) {
                setSelection({});
                return;
            }
            setSelection({
                left: ref.current[selectedValue].offsetLeft,
                width: ref.current[selectedValue].getBoundingClientRect().width
            });
        }
    }, [ref.current, selectedValue, segmentedControlWidth, options]);
    var handleClick = function (_value) {
        setValue(_value);
        onChange === null || onChange === void 0 ? void 0 : onChange(_value);
    };
    return (React.createElement(SegmentedControlWrapper, __assign({ className: className }, props),
        React.createElement(SegmentedControlBase, { ref: segmentedControlRef, size: size },
            React.createElement(Bracket, { bracketPosition: selectPosition }),
            options.map(function (opt) { return (React.createElement(ControlItem, { forwardedAs: "div", type: "phoenix", isDisabled: opt.isDisabled, isPressed: opt.value === selectedValue, key: opt.value, ref: function (el) { return (ref.current[opt.value] = el); }, onClick: function () { return !opt.isDisabled && handleClick(opt.value); } },
                React.createElement(React.Fragment, null,
                    opt.label,
                    opt.icon && opt.icon))); }))));
};
