import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/Swatch.scss';

const n = createNamespace('Swatch');

const Swatch = ({ swatchColors, selectedColorId, onClickColorCallback, isDropdownOpen }) => {
    const colors = isDropdownOpen ? swatchColors : swatchColors.filter(item => item.id === selectedColorId);
    const swatchItems = colors.map(color => {
        const modifiers = [
            ...(selectedColorId === color.id ? ['selected'] : []),
            ...(color.isDisabled ? ['disabled'] : [])
        ];
        return (
            <button
                {...n('item', modifiers).withTestId().props}
                key={color.id}
                style={{ backgroundColor: color.value }}
                title={color.name}
                type="button"
                disabled={color.isDisabled}
                onClick={() => { onClickColorCallback(color); }}
            />
        );
    });

    return (
        <div {...n('wrapper').withTestId().props}>
            {swatchItems}
        </div>
    );
};

Swatch.propTypes = {
    swatchColors: PropTypes.arrayOf(PropTypes.shape({
        id: PropTypes.string,
        name: PropTypes.string,
        value: PropTypes.string,
        isDisabled: PropTypes.bool
    })),
    selectedColorId: PropTypes.string,
    onClickColorCallback: PropTypes.func,
    isDropdownOpen: PropTypes.bool
};

Swatch.defaultProps = {
    swatchColors: [],
    selectedColorId: null,
    onClickColorCallback: () => {},
    isDropdownOpen: true
};
export default Swatch;
