import React from 'react';
import PropTypes from 'prop-types';
import ReactHtmlParser from 'react-html-parser';
import Button, { allowedThemes as buttonThemes } from '../button/Button';
import './styles/buttons-list.scss';
import { createNamespace } from '../../tools/namingTools';

const n = createNamespace('ButtonsList');

// Page Objects returns string with HTML
const parseStringHtml = htmlString => (
    ReactHtmlParser(htmlString)
);

const ButtonsList = ({
    data: { callToActions: { items, caption }, primaryButtonType }
}) => {
    if (!items || !items.length) {
        return null;
    }

    const renderButton = item => {
        const { label, enabled, isPrimary, url, actionType } = item;
        const buttonProps = Object.assign({
            url,
            key: label,
            extraClass: actionType && `btn-product-${actionType.toLowerCase()}`
        },
        isPrimary && {
            type: primaryButtonType || 'primary'
        },
        !enabled && {
            disabled: true
        });

        return (
            <Button {...buttonProps}>{label}</Button>
        );
    };

    return (
        <div {...n('container').props}>
            <div {...n('buttonGroup').withTestId('actions-container').withE2EId('actions-container').props}>
                {items.map(renderButton)}
            </div>
            {caption && (
                <div {...n('caption').props}>
                    {parseStringHtml(caption.text)}
                </div>
            )}
        </div>
    );
};

export const callToActionsShape = {
    items: PropTypes.arrayOf(PropTypes.shape({
        label: PropTypes.string,
        tooltip: PropTypes.string,
        isPrimary: PropTypes.bool,
        enabled: PropTypes.bool,
        url: PropTypes.string,
        actionType: PropTypes.string
    })),
    caption: PropTypes.shape({
        text: PropTypes.string
    })
};

ButtonsList.propTypes = {
    data: PropTypes.shape({
        callToActions: PropTypes.shape(callToActionsShape),
        primaryButtonType: PropTypes.oneOf(buttonThemes)
    })
};

ButtonsList.defaultProps = {
    data: {
        callToActions: {
            items: [{
                label: 'Default',
                tooltip: '',
                isPrimary: true,
                enabled: true,
                url: '',
                actionType: ''
            }],
            caption: {
                text: ''
            }
        },
        primaryButtonType: null
    }
};

export default ButtonsList;
