import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { variantOptionShape } from '../../../../constants/components/prop-types/product-variants';
import Swatch from '../../../../atoms/swatch/Swatch';
import Icon from '../../../../atoms/icon/Icon';
import { createNamespace } from '../../../../tools/namingTools';

import './styles/VariantOptionSwatch.scss';

const n = createNamespace('VariantOptionSwatch');

const VariantOptionSwatch = ({
    variantOption, selectedColorId, onClickColorCallback, isCondensed
}) => {
    const [isDropdownOpen, setDropdownOpen] = useState(true);
    const handleItemClick = () => {
        setDropdownOpen(!isDropdownOpen);
    };

    if (!variantOption) {
        return null;
    }

    const modifiers = isCondensed ? ['condensed'] : [];
    const swatchColors = variantOption.values && variantOption.values.map(optionValue => ({
        id: optionValue.code,
        name: optionValue.name,
        value: optionValue.hexcode,
        isDisabled: optionValue.isDisabled
    }));

    return (
        <div {...n('wrapper', modifiers).withTestId().props}>
            <div
                {...n('label', modifiers).withTestId().props}
                onClick={handleItemClick}
                onKeyDown={handleItemClick}
            >
                {variantOption.name}
                {' '}
                <Icon type={isDropdownOpen ? 'angleDown' : 'angleUp'} />
            </div>
            <Swatch
                swatchColors={swatchColors}
                selectedColorId={selectedColorId}
                onClickColorCallback={onClickColorCallback}
                hidden={isDropdownOpen}
            />
        </div>
    );
};

VariantOptionSwatch.propTypes = {
    variantOption: variantOptionShape.isRequired,
    selectedColorId: PropTypes.string,
    onClickColorCallback: PropTypes.func,
    isCondensed: PropTypes.bool
};

VariantOptionSwatch.defaultProps = {
    selectedColorId: null,
    onClickColorCallback: () => {},
    isCondensed: false
};

export default VariantOptionSwatch;
