import React from 'react';
import SelectableAccordionItem from './Item';
import { st, classes } from './SelectableAccordion.st.css.js';
import { VERTICAL_PADDING } from './constants';
/** SelectableAccordion */
class SelectableAccordion extends React.PureComponent {
    constructor() {
        super(...arguments);
        this.state = {
            openIndices: this._populateInitiallyOpenIndices(),
        };
        this._onItemChanged = (idx, open) => {
            const { type, onSelectionChanged } = this.props;
            let openIndices;
            if (open) {
                if (type === 'radio') {
                    openIndices = [idx];
                }
                else {
                    openIndices = [...this.state.openIndices, idx];
                }
            }
            else {
                openIndices = [...this.state.openIndices].filter(openIndex => idx !== openIndex);
            }
            this.setState({ openIndices }, () => onSelectionChanged && onSelectionChanged(openIndices));
        };
    }
    static getDerivedStateFromProps({ items }, state) {
        const controlled = items.some(item => item.open);
        return controlled
            ? {
                openIndices: items
                    .map((item, index) => (item.open ? index : null))
                    .filter(index => index !== null),
            }
            : state;
    }
    _populateInitiallyOpenIndices() {
        const { items } = this.props;
        const controlled = items.some(item => item.open);
        return items
            .map((item, index) => item[controlled ? 'open' : 'initiallyOpen'] ? index : null)
            .filter(index => index !== null);
    }
    render() {
        const { dataHook, className, items, verticalPadding, type } = this.props;
        const { openIndices } = this.state;
        return (React.createElement("div", { className: st(classes.root, className), "data-hook": dataHook }, items.map((item, idx) => (React.createElement(SelectableAccordionItem, { key: idx, idx: idx, type: type, verticalPadding: verticalPadding, onChange: (e, index, open) => {
                this._onItemChanged(index, open);
                item.onClick && item.onClick(e, { open });
            }, ...item, open: openIndices.includes(idx) })))));
    }
}
SelectableAccordion.defaultProps = {
    type: 'radio',
    items: [],
    verticalPadding: VERTICAL_PADDING.small,
};
SelectableAccordion.displayName = 'SelectableAccordion';
export default SelectableAccordion;
//# sourceMappingURL=SelectableAccordion.js.map