import React from 'react';
import get from 'lodash/get';
import isArray from 'lodash/isArray';
import './Styles.scss';
import PropTypes from 'prop-types';

class ConfigurationvariantSelection extends React.Component {
    static propTypes = {
        configurationvariants: PropTypes.array,
        ItemComponent: PropTypes.elementType,
        Carousel: PropTypes.elementType,
        selectedItem: PropTypes.string,
        showConfigurationVariantSelection: PropTypes.bool,
        onProceed: PropTypes.func,
    };

    constructor(props) {
        super(props);

        let initialSelection = null;

        if (props.selectedItem !== undefined) {
            initialSelection = props.selectedItem;
        } else {
            initialSelection = get(props.configurationvariants, '[0].identifier');
        }

        this.state = {
            selectedItem: initialSelection,
        };
    }

    onSelect = identifier => {
        this.setState({ selectedItem: identifier });
    };

    onProceed = identifier => {
        const { onProceed, showConfigurationVariantSelection } = this.props;
        onProceed(identifier, showConfigurationVariantSelection);
    };

    renderTitleComponent() {
        return null;
    }

    render() {
        const { configurationvariants, Carousel, ItemComponent } = this.props;

        if (!isArray(configurationvariants) || configurationvariants.length === 0) {
            return null;
        }

        return (
            <div className="configurationvariantSelection">
                {this.renderTitleComponent()}

                <Carousel className="configurationvariantItemWrapper">
                    {configurationvariants.map(item => (
                        <ItemComponent
                            identifier={item.identifier}
                            key={'configurationvariantItem_' + item.identifier}
                            item={item}
                            onSelect={this.onSelect}
                            selected={item.identifier === this.state.selectedItem}
                            onProceed={this.onProceed}
                        />
                    ))}
                </Carousel>
            </div>
        );
    }
}

export default ConfigurationvariantSelection;
