import React from 'react';
import PropTypes from 'prop-types';
import { variantOptionShape } from '../../../../constants/components/prop-types/product-variants';
import ContentDropdown from '../../../../atoms/content-dropdown/ContentDropdown';
import { createNamespace } from '../../../../tools/namingTools';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/VariantOptionList.scss';

const n = createNamespace('VariantOptionList');

const ItemTemplate = ({ optionValue, modifiers }) => (
    <div {...n('itemTemplate', modifiers).withTestId().props}>
        <div {...n('itemInfo', modifiers).withTestId().props}>
            <h2>{optionValue.name}</h2>
            <p>{optionValue.secondaryInformation}</p>
        </div>
        <div {...n('itemPrice', modifiers).withTestId().props}>
            {/* FIXME: Price should be dynamic */}
            {/* Starting at $999.99 */}
        </div>
    </div>
);

ItemTemplate.propTypes = {
    optionValue: PropTypes.shape({
        name: PropTypes.string,
        secondaryInformation: PropTypes.string
    }).isRequired,
    modifiers: PropTypes.arrayOf(PropTypes.string).isRequired
};

const VariantOptionList = ({
    variantOption, selectedItemId, onClickItemCallback, isCondensed
}) => {
    if (!variantOption) {
        return null;
    }
    const modifiers = isCondensed ? ['condensed'] : [];
    const optionList = variantOption.values && variantOption.values.map(optionValue => ({
        id: optionValue.code,
        content: <ItemTemplate modifiers={modifiers} optionValue={optionValue} />,
        isDisabled: optionValue.isDisabled
    }));

    const getSelectedItemContent = () => {
        const selectedItem = variantOption.values && variantOption.values.find(
            optionValue => optionValue.code === selectedItemId
        );
        return selectedItem && selectedItem.name ? <h2>{selectedItem.name}</h2> : null;
    };

    return (
        <div {...n('wrapper', modifiers).withTestId().props}>
            <ContentDropdown
                label={variantOption.name}
                items={optionList}
                selectedItemId={selectedItemId}
                selectedItemContentOverride={getSelectedItemContent()}
                closeOnItemClick={false}
                onClickItemCallback={onClickItemCallback}
            />
        </div>
    );
};

VariantOptionList.propTypes = {
    variantOption: variantOptionShape.isRequired,
    selectedItemId: PropTypes.string,
    onClickItemCallback: PropTypes.func,
    isCondensed: PropTypes.bool
};

VariantOptionList.defaultProps = {
    selectedItemId: null,
    onClickItemCallback: () => {},
    isCondensed: false
};

export default VariantOptionList;
