import { athenaConfig, athenaConfigOptions } from '../../global/athena-config.js';
import { handleHtml } from '../../global/helpers/athena-global-helper.js';
import { setProductPrice } from '../../global/helpers/athena-price-helper.js';
import { appendCategoryBanner } from './banners.js';

function resetNoProducts()
{
    document.getElementsByTagName('body')[0]?.classList.remove('no-products');
    const noProductsMessage = document.querySelector('.no-products-message');
    if(noProductsMessage) {
        noProductsMessage.remove();
    }

    const products = document.querySelector('.products');
    const messageContainer = products.querySelector('.no-products-message__container');
    if(messageContainer) {
        messageContainer.remove();
    }

    const swiper = products.querySelector('.swiper');
    if(swiper) {
        swiper.remove();
    }
}

/**
 * Handle Append or Prepend Products
 *
 * @param products
 * @param productContainer
 * @param insertProduct
 * @param isCategory
 * @param bestMatchSize
 * @param amounts
 * @param fetchMoreData
 * @param fetchLessData
 * @return {*|boolean}
 */
function appendSearchProducts(
    products,
    productContainer,
    insertProduct,
    isCategory,
    bestMatchSize,
    amounts,
    fetchMoreData = false,
    fetchLessData = false
) {
    if(products.length > 0) {
        resetNoProducts();

        athenaConfigOptions.shouldCutOff = fetchMoreData ? bestMatchSize <= amounts.to : bestMatchSize >= amounts.from && bestMatchSize <= amounts.to;

        let from = amounts.from;
        if(athenaConfigOptions.shouldCutOff && fetchLessData) {
            products = products.reverse();
        }

        products.forEach((item, key) => {
            const priceElement = setProductPrice('product', item);
            const searchForClickProduct = athenaConfigOptions.searchForClickProduct;

            if(insertProduct) {
                if(from > bestMatchSize && athenaConfigOptions.shouldCutOff) {
                    document.querySelector('.product-items-cutoff').prepend(
                        isCategory && item.type === 'category_banner' ?
                            appendCategoryBanner(item, key) :
                            insertContent(priceElement, searchForClickProduct, item, from)
                    );
                } else {

                    if(athenaConfigOptions.shouldCutOff && fetchLessData) {
                        productContainer.append(
                            isCategory && item.type === 'category_banner' ?
                                appendCategoryBanner(item, key) :
                                insertContent(priceElement, searchForClickProduct, item, from)
                        );
                    } else {
                        productContainer.prepend(
                            isCategory && item.type === 'category_banner' ?
                                appendCategoryBanner(item, key) :
                                insertContent(priceElement, searchForClickProduct, item, from)
                        );
                    }
                }
            } else {
                if(from > bestMatchSize && athenaConfigOptions.shouldCutOff) {
                    document.querySelector('.product-items-cutoff').append(
                        isCategory && item.type === 'category_banner' ?
                            appendCategoryBanner(item, key) :
                            insertContent(priceElement, searchForClickProduct, item, from)
                    );
                } else {
                    productContainer.append(
                        isCategory && item.type === 'category_banner' ?
                            appendCategoryBanner(item, key) :
                            insertContent(priceElement, searchForClickProduct, item, from)
                    );
                }
            }

            from++;
        });

        if(fetchLessData) {
            let productItems = Array.from(productContainer.querySelectorAll('.athena-page-product-item'));
            productItems = productItems.reverse();
            const itemsToReplace = [];
            productItems.forEach(productItem => {
                const dataKey = productItem.getAttribute('data-key');
                if(parseInt(dataKey) > bestMatchSize && athenaConfigOptions.shouldCutOff) {
                    itemsToReplace.push(productItem);
                    productItem.remove();
                }
            });

            itemsToReplace.forEach(item => {
                document.querySelector('.product-items-cutoff').prepend(item);
            });
        }

        if(athenaConfigOptions.shouldCutOff) {
            const cutoff = document.querySelector('.product-items-cutoff');

            const bestMatches = document.querySelector('.best-matches-div');
            if(bestMatches) {
                if(cutoff) {
                    cutoff.children.length > 0 ? bestMatches.style.display = 'block' : null;
                }
            }

            const alsoRelevant = document.querySelector('.also-relevant-div');
            if(alsoRelevant) {
                if(cutoff) {
                    cutoff.children.length > 0 ? alsoRelevant.style.display = 'block' : null;
                }
            }
        }
    } else {
        document.getElementsByTagName('body')[0]?.classList.add('no-products');
        const products = document.querySelector('.products');

        if(athenaConfig.isDemo) {
            const firstClickData = JSON.parse(localStorage.getItem('firstClickDataObject') || '{}');

            products.prepend(
                handleHtml(`
                    <div class="swiper">
                        <div class="swiper-wrapper"></div>
                        <div class="swiper-button-prev"></div>
                        <div class="swiper-button-next"></div>
                        
                        <div class="swiper-pagination"></div>
                    </div>
                `, '.swiper')
            );

            products?.prepend(
                handleHtml(`
                      <div class="no-products-message__container">
                            <span class="no-products-message">${athenaConfigOptions.noProductsMessage}</span>
                            <span class="no-products-message">Maybe you\`ll like these</span>
                      </div>
                `, '.no-products-message__container')
            );

            new Swiper('.swiper', {
                loop: true,
                direction: 'horizontal',
                autoHeight: true,
                observer: true,
                observeParents: true,
                spaceBetween: 20,
                slidesPerView: 1,

                navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                },

                breakpoints: {
                    640: {
                        slidesPerView: 2,
                    },
                    768: {
                        slidesPerView: 3,
                    },
                    1024: {
                        slidesPerView: 4,
                    },
                },
                virtual: {
                    slides: (function () {
                        const slides = [];

                        Object.entries(firstClickData).forEach((res)  => {
                            const responseKey = res[0];
                            const value = res[1];

                            if(responseKey === 'results') {
                                const products = value['product']['items'];

                                products?.forEach((item, from) => {
                                    const priceElement = setProductPrice('product', item);

                                    slides.push(`
                                    <li class="item product product-item athena-page-product-item" 
                                         ${item.id ? `data-element-id-${athenaConfigOptions.suffixArea}="${item.id}"` : ''}
                                         ${item.sku ? `data-element-sku-${athenaConfigOptions.suffixArea}="${item.sku}"` : ''}
                                         data-url-${athenaConfigOptions.suffixArea}="${item.link}"
                                         data-key="${from}"
                                    >
                                        <a class="athena-product-item-link"
                                             ${!athenaConfig.isDemo ? `
                                                href="${item.link}"
                                            ` : ''}
                                        >
                                            ${item.price && item.price.discount_percentage !== 0 && typeof item.price.discount_percentage !== 'undefined' ? `
                                                <span class="discount-div">
                                                    -${item.price.discount_percentage}%
                                                </span>
                                            ` : ''}
                                            <span class="athena-product-item-photo">
                                                ${item.image ? `
                                                    <img  
                                                        class="athena-autocomplete__image-product"
                                                        src="${item.image}" 
                                                        alt="${item.name}"
                                                    />
                                                ` : '' }  
                                            </span>   
                                        </a>
                                        <span class="athena-product-item-details"> 
                                            <a class="athena-page-product-link">
                                                <span class="athena-product-name" title="${item.name}">
                                                    ${item.highlighted_name ? item.highlighted_name : item.name}
                                                </span>
                                            </a>
                                            ${item.short_description ? `
                                                <div class="athena-product-item-description">${item.short_description}</div>
                                            ` : '' } 
                                            
                                            ${priceElement ? priceElement : ''}
                                        </span> 
                                        
                                    </li>
                                `)
                                });
                            }
                        });

                        return slides;
                    }())
                }
            });
        } else {
            products?.prepend(
                handleHtml(`
                      <div class="no-products-message__container">
                            <span class="no-products-message">${athenaConfigOptions.noProductsMessage}</span>
                      </div>
                `, '.no-products-message__container')
            );
        }
    }
}

/**
 * Insert Content Function
 *
 * @param priceElement
 * @param searchForClickProduct
 * @param item
 * @param key
 * @returns {DocumentFragment}
 */
function insertContent(priceElement, searchForClickProduct, item, key){
    return handleHtml(`
            <li class="item product product-item athena-page-product-item" 
                 data-terms-${athenaConfigOptions.suffixArea}="${searchForClickProduct}"
                 ${item.id ? `data-element-id-${athenaConfigOptions.suffixArea}="${item.id}"` : ''}
                 ${item.sku ? `data-element-sku-${athenaConfigOptions.suffixArea}="${item.sku}"` : ''}
                 data-url-${athenaConfigOptions.suffixArea}="${item.link}"
                 data-key="${key}"
            >
                <a class="athena-product-item-link"
                     ${!athenaConfig.isDemo ? `
                        href="${item.link}"
                    ` : ''}
                >
                    ${item.price && item.price.discount_percentage !== 0 && typeof item.price.discount_percentage !== 'undefined' ? `
                        <span class="discount-div">
                            -${item.price.discount_percentage}%
                        </span>
                    ` : ''}
                    <span class="athena-product-item-photo">
                        ${item.image ? `
                            <div class="athena-spinner-loader athena-spinner-loader-absolute"></div>
                            <img 
                                class="athena-product-image-photo" 
                                data-src="${item.image}" 
                                alt="${item.name}"
                                style="visibility: hidden"
                            />
                            
                            <span class="find-visual-similar">Find similar style</span>
                            
                        ` : '' }  
                    </span>   
                </a>
                <span class="athena-product-item-details"> 
                    <a class="athena-page-product-link">
                        <span class="athena-product-name" title="${item.name}">
                            ${item.highlighted_name ? item.highlighted_name : item.name}
                        </span>
                    </a>
                    ${item.short_description ? `
                        <div class="athena-product-item-description">${item.short_description}</div>
                    ` : '' } 
                    ${priceElement ? priceElement : ''}
                </span> 
            </li>
        `, `.athena-page-product-item`);
}

export {
    appendSearchProducts
}
