import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../../../tools/namingTools';
import Button from '../../../../atoms/button/Button';
import Icon from '../../../../atoms/icon/Icon';
import UpgradeModal from '../../../upgrade-modal/UpgradeModal';
import { SelectionPreviewComponent } from '../../../../atoms/selection-preview/SelectionPreview';
import { CTA_BUY, CTA_BUY_MORE, CTA_ADD_TO_CART, CTA_MANAGE_APP,
    CTA_UPDATE_CART_ITEM, CTA_CANCEL, CART_URL, CTA_UPGRADE } from '../../../../constants/actions';
import { handleBuyAction, handleUpdateAction, handleAddToCartAction,
    handleFollowUrlAction } from '../../../../tools/callToActions';
import { callToActionListShape } from '../../../../constants/prop-types/application/call-to-actions';
import { configuratorPropTypes, selectedEditionPropTypes } from '../../../../constants/prop-types/application/configurator';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/VariantCta.scss';

const n = createNamespace('VariantCta');

const VariantCta = ({
    callToActions,
    configurator,
    isCtaDisabled,
    isFullscreen,
    selectedAddons,
    selectedEdition
}) => {
    const i18n = { ...SelectionPreviewComponent.defaultProps.data.configurator.i18n, ...configurator.i18n };
    const buyActions = callToActions ? callToActions.items : [];
    const fullscreenModifier = isFullscreen && 'fullscreen';
    const [upgradeDetails, setUpgradeDetails] = useState(null);

    const handleUpgradeAction = action => {
        setUpgradeDetails(action.popup);
    };

    const handleActionTypes = item => {
        let buttonStyle;
        let icon;

        switch (item.actionType) {
            case CTA_MANAGE_APP:
                buttonStyle = 'emphasisAlt';
                break;
            case CTA_ADD_TO_CART:
                buttonStyle = 'emphasisAlt';
                icon = 'cart';
                break;
            case CTA_BUY:
            case CTA_BUY_MORE:
                buttonStyle = 'emphasis';
                break;
            case CTA_UPDATE_CART_ITEM:
                buttonStyle = 'primary';
                break;
            default:
                buttonStyle = item.isPrimary ? 'primary' : 'secondary';
        }
        return { buttonStyle, icon };
    };

    const handleClick = action => {
        const { actionType } = action;

        switch (actionType) {
            case CTA_MANAGE_APP:
            case CTA_CANCEL:
                return handleFollowUrlAction(action);
            case CTA_ADD_TO_CART:
                return handleAddToCartAction(
                    selectedEdition,
                    selectedAddons,
                    configurator.productId,
                    configurator.crossSellManagementEnabled
                );
            case CTA_UPGRADE:
                return handleUpgradeAction(action);
            case CTA_UPDATE_CART_ITEM:
                return handleUpdateAction(
                    action,
                    selectedEdition,
                    selectedAddons,
                    configurator.productId,
                    configurator.crossSellManagementEnabled,
                    configurator.editionInCartItemId
                );
            case CTA_BUY:
            case CTA_BUY_MORE:
            default:
                return handleBuyAction(
                    action,
                    selectedEdition,
                    selectedAddons,
                    configurator.productId,
                    configurator.crossSellManagementEnabled
                );
        }
    };

    const renderActionButtons = action => {
        const dataId = action.actionType.toLowerCase();
        const actionTypeData = handleActionTypes(action);
        const buttonModifiers = [actionTypeData.icon && 'with-icon', fullscreenModifier];

        // if there is an UPDATE_CART_ITEM action, it means that we also need
        // a CANCEL button which is not defined in calltoactions
        const hasCancelButton = action.actionType === CTA_UPDATE_CART_ITEM;

        const cancelButton = hasCancelButton ? (
            <div {...n('button').props} key="cancel-action">
                <Button
                    wide={!isFullscreen}
                    onClick={() => handleClick({
                        url: CART_URL,
                        actionType: CTA_CANCEL
                    })}
                    ctaType={CTA_CANCEL}
                >
                    {i18n.cancel}
                </Button>
            </div>
        ) : null;

        return (
            <React.Fragment key={action.actionType}>
                <div {...n('button', buttonModifiers).withTestId('actions-container').withE2EId('actions-container').props} key="main-action">
                    <Button
                        data-testid={`button:${dataId}:product`}
                        type={actionTypeData.buttonStyle}
                        wide={!isFullscreen}
                        className={dataId && `btn-${dataId}`}
                        onClick={() => handleClick(action)}
                        ctaType={action.actionType}
                        disabled={isCtaDisabled}
                    >
                        {actionTypeData.icon && <Icon type="cart" {...n('buttonIcon').props} />}
                        {action.label}
                    </Button>
                </div>
                {cancelButton}
            </React.Fragment>

        );
    };

    const renderModal = () => {
        const handleClose = () => {
            setUpgradeDetails(null);
        };
        return (upgradeDetails && <UpgradeModal upgrades={upgradeDetails} handleClose={handleClose} />);
    };

    return (
        <>
            <div {...n('buttons', [fullscreenModifier]).props}>
                {buyActions.map(renderActionButtons)}
            </div>
            {renderModal()}
        </>
    );
};

VariantCta.propTypes = {
    callToActions: callToActionListShape,
    configurator: configuratorPropTypes,
    isCtaDisabled: PropTypes.bool,
    isFullscreen: PropTypes.bool,
    selectedAddons: PropTypes.arrayOf(PropTypes.shape({})),
    selectedEdition: selectedEditionPropTypes
};

VariantCta.defaultProps = {
    callToActions: { items: [] },
    configurator: {},
    isCtaDisabled: false,
    isFullscreen: false,
    selectedAddons: [],
    selectedEdition: {
        name: '',
        plans: [
            {
                costs: {
                    unitPrice: [
                        {
                            usageRange: [
                                {
                                    formattedFullPriceElements: []
                                }
                            ]
                        }
                    ]
                }
            }
        ]
    }
};
export default VariantCta;
