import React from 'react';
import PropTypes from 'prop-types';
import withListener from '../withListener';
import { createNamespace } from '../../tools/namingTools';
import { generateUniqueID } from '../../tools/helpers';
import BundleLogo from '../../atoms/bundle-logo/BundleLogo';
import './styles/ProductBundleDescription.scss';

const n = createNamespace('ProductBundleDescription');

const renderBundle = item => {
    if (!item.card) {
        return null;
    }

    return (
        <div {...n('bundleCard').withTestId().props} key={generateUniqueID([item.id, item.card.title])}>
            <BundleLogo data={item.card} />
        </div>
    );
};

export const ProductBundleDescriptionComponent = ({
    data: {
        overview,
        items,
        i18n
    }
}) => {
    if (!overview) {
        return null;
    }
    const i18nWithDefaults = { ...ProductBundleDescriptionComponent.defaultProps.data.i18n, ...i18n };

    const { title, description } = overview;
    return (
        <section {...n('wrapper').props}>
            {title && <h1 {...n('title').withTestId().props}>{title}</h1>}
            {description && (
                <p {...n('description').withTestId().props} dangerouslySetInnerHTML={{ __html: description }} />
            )}
            {items && items.length ? (
                <div {...n('bundleWrapper').props}>
                    <div {...n('subtitle').withTestId().props}>{i18nWithDefaults.bundleIncludes}</div>
                    <div {...n('bundleList').withTestId().props}>
                        {items.map(item => renderBundle(item))}
                    </div>
                </div>
            ) : ''}
        </section>
    );
};

export const bundleLogoShape = PropTypes.shape({
    id: PropTypes.number,
    card: PropTypes.shape({
        title: PropTypes.string,
        logoSrc: PropTypes.string,
        logoSrcset: PropTypes.shape({
            default: PropTypes.string
        })
    })
});

ProductBundleDescriptionComponent.schema = () => ({
    name: 'ProductBundleDescription',
    title: 'uieditor.sfbComponent.productBundleDescription.title',
    iconName: '',
    form: {
    },
    marketplaceData: {
        overview: 'bundle.overview',
        items: 'bundle.items',
        i18n: 'bundle.i18n'
    }
});

ProductBundleDescriptionComponent.propTypes = {
    data: PropTypes.shape({
        overview: PropTypes.shape({
            description: PropTypes.string,
            title: PropTypes.string
        }),
        items: PropTypes.arrayOf(bundleLogoShape),
        i18n: PropTypes.shape({
            bundleIncludes: PropTypes.string
        })

    })
};

ProductBundleDescriptionComponent.defaultProps = {
    data: {
        overview: {},
        items: [],
        i18n: {
            bundleIncludes: 'Bundle Package Includes'
        }
    }
};

export default withListener(ProductBundleDescriptionComponent);
