import { __assign, __read, __rest, __spreadArray } from "tslib";
import React, { forwardRef } from "react";
import { useStateProps } from "../hooks/useStateProps";
import { CheckBoxGroupStyled, CheckBoxStyled } from "./styles";
var CheckBoxGroup = forwardRef(function (_a, ref) {
    var options = _a.options, _b = _a.direction, direction = _b === void 0 ? "column" : _b, className = _a.className, value = _a.value, classNameCheckBox = _a.classNameCheckBox, onChange = _a.onChange, isDisabled = _a.isDisabled, name = _a.name, props = __rest(_a, ["options", "direction", "className", "value", "classNameCheckBox", "onChange", "isDisabled", "name"]);
    var _c = __read(useStateProps(value), 2), selectedItems = _c[0], setSelectedItems = _c[1];
    var getChecked = function (_value) {
        return (selectedItems === null || selectedItems === void 0 ? void 0 : selectedItems.findIndex(function (v) { return v === _value; })) !== -1;
    };
    var handleChange = function (event, selectedValue) {
        var newValue = [];
        if (getChecked(selectedValue)) {
            newValue = selectedItems === null || selectedItems === void 0 ? void 0 : selectedItems.filter(function (item) { return item !== selectedValue; });
        }
        else {
            newValue = __spreadArray([], __read(selectedItems), false);
            newValue.push(selectedValue);
        }
        setSelectedItems(newValue);
        onChange === null || onChange === void 0 ? void 0 : onChange(event, newValue);
    };
    return (React.createElement(CheckBoxGroupStyled, __assign({}, props, { ref: ref, className: className, direction: direction, "data-element": "checkBox-group" }), options.map(function (option) { return (React.createElement(CheckBoxStyled, { key: option.value, label: option.label, isDisabled: isDisabled || option.isDisabled, isChecked: getChecked(option.value), onChange: function (event) { return handleChange(event, option.value); }, className: classNameCheckBox, name: name })); })));
});
CheckBoxGroup.displayName = "CheckBoxGroup";
export default CheckBoxGroup;
