import {registerCheckoutFilters} from '@woocommerce/blocks-checkout';
import {useSelect} from '@wordpress/data';
import {useEffect, useState} from '@wordpress/element';
import {registerPlugin} from '@wordpress/plugins';

const modifyCartItemClass = (defaultValue, extensions, args) => {
    const campaignsData = args.cartItem?.item_data ? args.cartItem.item_data.filter(data => data.name === 'ywdpd-rules-applied') : [];
    if (campaignsData.length > 0) {
        return defaultValue + ' ywdpd-item-width-badge--' + args.cartItem.id;
    }
    return defaultValue;
}

registerCheckoutFilters('ywdpd-add-cart-item-class', {
    cartItemClass: modifyCartItemClass,
});

const render = () => {
    const cartItems = useSelect((select) => select('wc/store/cart').getCartData().items);

    useEffect(() => {
        setTimeout( function (){
            const cartHtml = document.querySelector('.wc-block-cart__main') || document.querySelector('.wc-block-components-order-summary__content');
            if (cartHtml !== null) {
                const oldBadges = cartHtml.querySelectorAll('.ywdpd-sale-badge');
                oldBadges.forEach(oldBadge => {
                    oldBadge.remove();
                });
                const elementsWithBadge = document.querySelectorAll('[class*=ywdpd-item-width-badge]');
                elementsWithBadge.forEach(elementWithBadge => {

                    const classList = Array.from(elementWithBadge.classList);
                    const className = classList.filter(classList => classList.includes('ywdpd-item-width-badge')).shift();
                    const itemID = className.split('--')[1];

                    const items = cartItems.filter(cartItem => cartItem.id === parseInt(itemID));
                    let item = false;
                    if (items.length > 1) {
                        item = items.filter(item => item.item_data.filter(data => data.name === 'ywdpd-rules-applied').length === 1).shift();
                    } else {
                        item = items.shift();

                    }
                    const campaignsData = item ? item.item_data.filter(data => data.name === 'ywdpd-rules-applied') : [];
                    if (campaignsData.length > 0) {
                        const names = campaignsData[0].value.split(',');
                        names.forEach(name => {
                            const id = name.toLowerCase().replaceAll(' ', '-');
                            if (!elementWithBadge.querySelector('#' + id)) {
                                const badgeHtml = document.createElement('div');
                                badgeHtml.id = id;
                                badgeHtml.className = 'ywdpd-sale-badge wc-block-components-product-badge wc-block-components-sale-badge';
                                badgeHtml.innerHTML = "<span>" + name + "</span>";
                                badgeHtml.style = 'margin-right:5px';

                                if (Array.from(cartHtml.classList).includes('wc-block-components-order-summary__content')) {
                                    elementWithBadge.querySelector('.wc-block-components-order-summary-item__description').insertBefore(badgeHtml, elementWithBadge.querySelector('.wc-block-components-order-summary-item__description').children[1]);
                                } else {
                                    elementWithBadge.querySelector('.wc-block-cart-item__wrap').insertBefore(badgeHtml, elementWithBadge.querySelector('.wc-block-cart-item__wrap').children[2]);
                                }
                            }
                        });
                    }

                });
            }
        }, 500 );

    },[cartItems]);


}
registerPlugin('ywdpd-badge-discount', {
    render,
    scope: 'woocommerce-checkout',
});

