import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import Image from '../image/Image';
import { PRODUCT_DEFAULT_IMG } from '../../constants/images';

import './styles/CartEditionPreview.scss';

const n = createNamespace('CartEditionPreview');

export const parseEditionNames = (editions = []) => editions.map(edition => edition.name).join(', ');

const CartEditionPreview = ({
    branding,
    editions,
    variant,
    i18n
}) => {
    const i18nWithDefaults = { ...CartEditionPreview.defaultProps.i18n, ...i18n };
    const { name, vendor, iconUrl } = branding;

    if (!name) {
        return null;
    }

    const hasEditions = Boolean(editions && editions.length);

    return (
        <div {...n('wrapper', variant).props}>
            <div {...n('imageWrapper').withTestId().props}>
                <Image
                    {...n('image').props}
                    src={iconUrl || CartEditionPreview.defaultProps.branding.iconUrl}
                    alt={name}
                    withBorder
                />
            </div>
            <div {...n('content').props}>
                {name && (
                    <h4 {...n('title').withTestId().props}>{name}</h4>
                )}
                {(vendor || hasEditions) && (
                    <div {...n('info').props}>
                        {vendor && (
                            <div>
                                {i18nWithDefaults.vendor && `${i18nWithDefaults.vendor}: `}
                                <span {...n('vendor').withTestId().props}>{vendor}</span>
                            </div>
                        )}
                        {hasEditions && (
                            <div>
                                {i18nWithDefaults.edition && `${i18nWithDefaults.edition}: `}
                                <span {...n('editions').withTestId().props}>{parseEditionNames(editions)}</span>
                            </div>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
};

CartEditionPreview.propTypes = {
    branding: PropTypes.shape({
        name: PropTypes.string,
        vendor: PropTypes.string,
        iconUrl: PropTypes.string
    }),
    variant: PropTypes.string,
    editions: PropTypes.arrayOf(PropTypes.shape()),
    i18n: PropTypes.shape({
        edition: PropTypes.string,
        vendor: PropTypes.string
    })
};

CartEditionPreview.defaultProps = {
    branding: {
        iconUrl: PRODUCT_DEFAULT_IMG
    },
    editions: [],
    variant: null,
    i18n: {
        edition: 'Edition',
        vendor: 'By'
    }
};

export default CartEditionPreview;
