import { CTA_LEAD_GEN, CTA_BUY_CROSS_SELL,
    CTA_ADD_TO_CART_CROSS_SELL, CTA_UPDATE_CART_ITEM_CROSS_SELL,
    CART_URL, CTA_ADD_TO_CART, CTA_CONFIGURE } from '../constants/actions';

import { getCtaApiEndpoint, navigateTo } from './urlTools';

const getPricingPlanId = ({ id, plans = [] }) => {
    if (plans && plans.length) {
        return plans[0].uuid;
    }
    return id;
};

const getAddonIds = addons => (addons
    ? addons.map(addon => getPricingPlanId(addon?.edition?.[0] || {})).filter(addonId => !!addonId)
    : []);

const getCartLink = (
    selectedEdition = {},
    selectedAddons = [],
    urlCreator = {}
) => {
    const { addonParam } = urlCreator;
    const url = urlCreator.base;

    const addonIds = getAddonIds(selectedAddons);

    const queryParams = [
        `${urlCreator.editionParam}=${getPricingPlanId(selectedEdition)}`,
        ...addonIds.map(addonId => `${addonParam}=${addonId}`)
    ];

    const glue = url.indexOf('?') === -1 ? '?' : '&';

    return `${url}${glue}${queryParams.join('&')}`;
};

export const filterBundleActions = cta => {
    if (!cta) {
        return null;
    }

    return cta.actionType !== CTA_LEAD_GEN;
};

export const parsePricingAction = (action = {}) => {
    const transformedAction = { ...action };
    if (action.actionType === CTA_LEAD_GEN) {
        transformedAction.url = action.leadPageUrl;
    }
    return transformedAction;
};

export const parsePricingActions = actions => ({
    caption: actions && actions.caption ? { ...actions.caption } : undefined,
    items: actions && actions.items ? actions.items.map(parsePricingAction) : []
});

export const getCrossSellActionUrl = (
    action,
    edition,
    addons,
    productId,
    urlCreator = {},
    editionInCartItemId = null
) => {
    const { actionType } = action;
    const editionPricingPlanId = edition?.plans?.[0]?.uuid;
    const addonsPricingPlanIds = addons.map(addon => addon?.edition?.[0]?.plans?.[0]?.uuid);

    const queryParams = [
        `productId=${productId}`,
        `type=${actionType}`,
        'crossSellManagement=true',
        `eppid=${editionPricingPlanId}`,
        ...addonsPricingPlanIds.map(appId => `appid=${appId}`),
        `previousCTA=${actionType}`
    ];

    if (editionInCartItemId) {
        queryParams.push(`${urlCreator.editionInCartParam}=${editionInCartItemId}`);
    }

    return getCtaApiEndpoint(queryParams.join('&'));
};

const handleCtaRedirectAndCrossSell = (
    action,
    edition,
    addons,
    productId,
    crossSellManagementEnabled,
    crossSellActionType,
    editionInCartItemId
) => {
    if (crossSellManagementEnabled) {
        const crossSellAction = {
            actionType: crossSellActionType
        };

        navigateTo(getCrossSellActionUrl(
            crossSellAction,
            edition,
            addons,
            productId,
            action.urlCreator,
            editionInCartItemId
        ));
        return;
    }

    const redirectCartLink = getCartLink(
        edition,
        addons,
        action.urlCreator
    );

    window.location.assign(redirectCartLink);
};

export const handleUpdateAction = (
    action,
    edition,
    addons,
    productId,
    crossSellManagementEnabled,
    editionInCartItemId
) => {
    handleCtaRedirectAndCrossSell(
        action,
        edition,
        addons,
        productId,
        crossSellManagementEnabled,
        CTA_UPDATE_CART_ITEM_CROSS_SELL,
        editionInCartItemId
    );
};

export const handleBuyAction = (
    action,
    edition,
    addons,
    productId,
    crossSellManagementEnabled
) => {
    handleCtaRedirectAndCrossSell(
        action,
        edition,
        addons,
        productId,
        crossSellManagementEnabled,
        CTA_BUY_CROSS_SELL
    );
};

export const handleAddToCartAction = (
    edition,
    addons = [],
    productId,
    crossSellManagementEnabled,
    isNonStackable = false,
    hasAddons = false
) => {
    if (crossSellManagementEnabled) {
        const addToCartCrossSellAction = {
            actionType: CTA_ADD_TO_CART_CROSS_SELL
        };
        navigateTo(getCrossSellActionUrl(addToCartCrossSellAction, edition, addons, productId));
        return;
    }

    window.AD_addToCart(
        getPricingPlanId(edition),
        getAddonIds(addons),
        null,
        isNonStackable,
        hasAddons
    );
};

export const getAddDomainToCartCrossSellUrl = (cartItemId, productId, editionPricingPlanId, addonIds, domains) => {
    const params = [
        `productId=${productId}`,
        `eppid=${editionPricingPlanId}`,
        `type=${CTA_UPDATE_CART_ITEM_CROSS_SELL}`,
        `cartItemId=${cartItemId}`,
        ...addonIds.map(addonEppId => `appid=${addonEppId}`),
        ...domains.map(domainData => `domain=${domainData.name},${domainData.pricingPlan}`)
    ].join('&');
    return getCtaApiEndpoint(params);
};

export const handleAddDomainToCartAction = (cartItemId, productId, editionPricingPlanId, addonIds, domains) => {
    navigateTo(getAddDomainToCartCrossSellUrl(cartItemId, productId, editionPricingPlanId, addonIds, domains));
};

export const handleFollowUrlAction = action => {
    window.location.assign(action.url);
};

export const handleReplaceEdition = (
    cartId,
    oldEditionCartItemId,
    newEditionPricingPlanId,
    userUuid,
    companyUuid,
    nonStackableProduct,
    hasAddons
) => {
    if (!userUuid || !companyUuid) {
        console.error('Replace edition error: user not logged in');
        return;
    }

    if (!cartId) {
        console.error('Replace edition error: cart id undefined');
        return;
    }

    if (!oldEditionCartItemId || !newEditionPricingPlanId) {
        console.error('Replace edition error: old edition and new edition required');
        return;
    }

    window.AD_replaceEditionInCart(
        cartId,
        oldEditionCartItemId,
        newEditionPricingPlanId,
        userUuid,
        companyUuid,
        nonStackableProduct,
        hasAddons
    );
};

export const handleUpdateAddonsNonStackable = (
    cartId,
    oldEditionCartItemId,
    newEditionPricingPlanId,
    newEditionAddonPricingPlanIds,
    userUuid,
    companyUuid
) => {
    if (!userUuid || !companyUuid) {
        console.error('Update addons non-stackable error: user not logged in');
        return;
    }

    if (!cartId) {
        console.error('Update addons non-stackable error: cart id undefined');
        return;
    }

    if (!oldEditionCartItemId || !newEditionPricingPlanId) {
        console.error('Update addons non-stackable error: old edition and new edition required');
        return;
    }

    window.AD_updateAddonsNonStackableInCart(
        cartId,
        oldEditionCartItemId,
        newEditionPricingPlanId,
        newEditionAddonPricingPlanIds,
        userUuid,
        companyUuid
    );
};

export const redirectToCart = () => {
    navigateTo(CART_URL);
};

export const getButtonTypeForCta = (callToAction, isSelected) => {
    let buttonType;
    if (callToAction?.actionType === CTA_ADD_TO_CART) {
        buttonType = 'emphasisAlt';
    } else if (isSelected) {
        buttonType = 'primary-outline';
    } else {
        buttonType = 'primary';
    }

    return buttonType;
};

export const canReplaceEdition = (callToAction, nonStackableProduct, hasAddons) => (
    (nonStackableProduct && callToAction?.actionType === CTA_ADD_TO_CART)
    || (
        nonStackableProduct && hasAddons && callToAction?.actionType === CTA_CONFIGURE
    )
);

export const getActionLabel = (
    configuratorMode,
    isSelected,
    i18n,
    callToAction,
    isAddedToCart,
    nonStackableProduct,
    hasAddons
) => {
    if (configuratorMode) {
        return isSelected ? i18n.selected : i18n.select;
    } if (isAddedToCart && canReplaceEdition(callToAction, nonStackableProduct, hasAddons)) {
        return i18n.cart.addedToCart;
    }
    return callToAction ? callToAction.label : null;
};
