import { __assign, __rest } from "tslib";
import React, { forwardRef, useMemo } from "react";
import { DropdownListWrapper, DropdownItemsWrapper, DividerStyled } from "../../styles";
import DropdownItem from "../DropdownItem";
import { withDefaultGetters } from "../../helpers";
var DropdownList = forwardRef(function (props, ref) {
    var _a = withDefaultGetters(props), items = _a.items, _b = _a.direction, direction = _b === void 0 ? "bottom" : _b, getItemKey = _a.getItemKey, getItemOnClick = _a.getItemOnClick, getItemLeadContent = _a.getItemLeadContent, getItemGroupId = _a.getItemGroupId, getItemDisabled = _a.getItemDisabled, getItemAttributes = _a.getItemAttributes, getItemLabel = _a.getItemLabel, className = _a.className, onItemClick = _a.onItemClick, sortGroup = _a.sortGroup, width = _a.width, otherProps = __rest(_a, ["items", "direction", "getItemKey", "getItemOnClick", "getItemLeadContent", "getItemGroupId", "getItemDisabled", "getItemAttributes", "getItemLabel", "className", "onItemClick", "sortGroup", "width"]);
    var groups = useMemo(function () {
        var _groups = items.reduce(function (result, x) {
            if (getItemGroupId(x)) {
                var index = result.length &&
                    result[0].length &&
                    result.findIndex(function (r) {
                        return getItemGroupId(r[0]) ===
                            getItemGroupId(x);
                    });
                if (index !== -1) {
                    result[index].push(x);
                }
                else {
                    result.push([]);
                    result[result.length - 1].push(x);
                }
            }
            else {
                result[0].push(x);
            }
            return result;
        }, [[]]);
        return sortGroup
            ? _groups.sort(function (items1, items2) {
                return sortGroup(getItemGroupId(items1[0]) || 1, getItemGroupId(items2[0]) || -1);
            })
            : _groups;
    }, [items]);
    return (React.createElement(DropdownListWrapper, __assign({ ref: ref, direction: direction, className: className, width: width }, otherProps), groups.map(function (gItems, index) { return (React.createElement(React.Fragment, { key: "dropdown-group-" + getItemGroupId(gItems[0]) },
        React.createElement(DropdownItemsWrapper, null, gItems.map(function (item) { return (React.createElement(DropdownItem, { key: getItemKey(item), item: item, getItemAttributes: getItemAttributes, getItemLabel: getItemLabel, getItemDisabled: getItemDisabled, getItemLeadContent: getItemLeadContent, getItemOnClick: getItemOnClick, onItemClick: onItemClick })); })),
        index !== groups.length - 1 && React.createElement(DividerStyled, null))); })));
});
DropdownList.displayName = "DropdownList";
export default DropdownList;
