import { athenaConfig, athenaConfigOptions } from '../../global/athena-config.js';
import { handleHtml } from '../../global/helpers/athena-global-helper.js';
import filterSearch from '../../global/helpers/filter-search.js';

/**
 * Append Sidebar Filters
 *
 * @param filters
 * @param activeFilters
 * @param collectionPrice
 */
function appendSidebarFilters(
    filters,
    activeFilters,
    collectionPrice,
) {
    filters.forEach(filter => {

        athenaConfigOptions.searchSidebar.append(
            handleHtml(`
                <div class="athena-search-filter" data-filter-type="${filter.type}">
                   <p class="athena-filter-title">${filter.title}</p>
                   <div id="athena-filter-container-${filter.type}" class="athena-filter-container">
                        <div class="athena-filter-container__inner"></div>
                   </div>
                </div>
            `, '.athena-search-filter')
        );

        if(filter.type !== 'price') {
            if(filter.array) {
                filter.array.forEach(element => {

                    const urlParams = encodeURIComponent(JSON.stringify(element.url_params));
                    const filterParent = document.querySelector(`#athena-filter-container-${filter.type} .athena-filter-container__inner`);

                    // Check swatches
                    if(element.hax_code) {
                        if(element.type_id === '0') {
                            filterParent?.append(
                                handleHtml(`
                                    <div data-value="${urlParams !== 'undefined' && urlParams}" data-search-value="${element.option_label}" class="athena-filter-item ${element.selected ? 'selected-filter' : ''} athena-filter-item-swatches">
                                         <span class="search-filter-label">${element.option_label}</span>
                                         <input type="checkbox" ${element.selected ? 'checked="true"' : ''} class="athena-filter-checkbox athena-filter-checkbox-swatch"/>
                                         <span class="checkmark"></span>
                                    </div>
                                `, '.athena-filter-item')
                            );
                        } else if(element.type_id === '1') {
                            filterParent?.append(
                                handleHtml(`
                                    <div data-value="${urlParams !== 'undefined' && urlParams}" data-search-value="${element.option_label}" class="athena-filter-item ${element.selected ? 'selected-filter' : ''} athena-filter-item-swatches search-swatch-background">
                                         <span class="search-swatch-label">${element.option_label}</span>
                                         <span class="search-swatch-value-background" style="background-color: ${element.hax_code}"></span>
                                         <input type="checkbox" ${element.selected ? 'checked="true"' : ''} class="athena-filter-checkbox athena-filter-checkbox-swatch"/>
                                         <span class="checkmark"></span>
                                    </div>
                                `, '.athena-filter-item')
                            );
                        } else if(element.type_id === '2') {
                            filterParent?.append(
                                handleHtml(`
                                    <div data-value="${urlParams !== 'undefined' && urlParams}" data-search-value="${element.option_label}" class="athena-filter-item ${element.selected ? 'selected-filter' : ''} athena-filter-item-swatches search-swatch-background">
                                         <span class="search-swatch-label">${element.option_label}</span>
                                         <span class="search-swatch-value-background" style="background: url(${element.hax_code})"></span>
                                         <input type="checkbox" ${element.selected ? 'checked="true"' : ''} class="athena-filter-checkbox athena-filter-checkbox-swatch"/>
                                         <span class="checkmark"></span>
                                    </div>
                                `, '.athena-filter-item')
                            );
                        }
                    } else {
                        filterParent?.append(
                            handleHtml(`
                                <div data-value="${urlParams !== 'undefined' && urlParams}" data-search-value="${element.option_label}" class="athena-filter-item ${element.selected ? 'selected-filter' : ''}">
                                    <span class="search-filter-label">${element.option_label}</span>
                                    <input type="checkbox" ${element.selected ? 'checked="true"' : ''} class="athena-filter-checkbox"/>
                                    <span class="checkmark"></span>
                                </div>
                            `, '.athena-filter-item')
                        );
                    }
                });

                filterSearch(
                    filter.type,
                    filter.array,
                    '.athena-sidebar',
                    '.athena-filter-container',
                    ['.search-swatch-label', '.search-filter-label'],
                    '.athena-filter-item',
                    filter.title
                );

                const filterChildren = document.querySelectorAll('.athena-filter-container');
                if (!filterChildren) {
                    return;
                }

                filterChildren.forEach(filterChild => {
                    const count = filterChild.querySelector('.athena-filter-container__inner')?.children.length;
                    if(typeof count !== 'undefined') {

                        if(filterChild.closest('.athena-search-filter')?.getAttribute('data-filter-type') === 'velicina'){
                            if(count <= athenaConfigOptions.showMoreCutoffItemsSize){
                                return;
                            }

                            if (!filterChild?.querySelector('.athena-cutoff__container')){
                                filterChild?.append(
                                    handleHtml(`
                                <div class="athena-cutoff__container athena-cutoff__container-filters-landing">
                                    <span class="athena-cutoff__button athena-cutoff__show-more-button athena-helper-show">${athenaConfigOptions.showMoreButtonName}</span>
                                    <span class="athena-cutoff__button athena-cutoff__show-less-button">${athenaConfigOptions.showLessButtonName}</span>
                                    <span class="icon-arrow"></span>
                                </div>
                            `, '.athena-cutoff__container')
                                );
                            }
                        }else{
                            if(count <= athenaConfigOptions.showMoreCutoffItems){
                                return;
                            }

                            if (!filterChild?.querySelector('.athena-cutoff__container')){
                                filterChild?.append(
                                    handleHtml(`
                                <div class="athena-cutoff__container athena-cutoff__container-filters-landing">
                                    <span class="athena-cutoff__button athena-cutoff__show-more-button athena-helper-show">${athenaConfigOptions.showMoreButtonName}</span>
                                    <span class="athena-cutoff__button athena-cutoff__show-less-button">${athenaConfigOptions.showLessButtonName}</span>
                                    <span class="icon-arrow"></span>
                                </div>
                            `, '.athena-cutoff__container')
                                );
                            }
                        }

                    }
                });
            } else {
                const filterParent = document.querySelector(`#athena-filter-container-${filter.type}`);
                filterParent.closest('.athena-search-filter').remove();
            }
        } else {
            const filterParent = document.querySelector(`#athena-filter-container-${filter.type}`);

            if(collectionPrice.highest_price > 0 && collectionPrice.lowest_price >= 0) {
                filterParent?.append(
                    handleHtml(`
                        <div class="search-filter-price-range">
                            <input
                                type="range"
                                multiple="multiple"
                                min="${collectionPrice.lowest_price}"
                                max="${collectionPrice.highest_price}"
                                unit="${athenaConfig.priceRangeUnit}"
                                unitPlacement="${athenaConfig.priceRangePlacement}"
                                value=""
                                id="price-range-slider"
                                minAll="${collectionPrice.lowest_price_with_filters}"
                                maxAll="${collectionPrice.highest_price_with_filters}"
                            />
                        </div>
                `, '.search-filter-price-range')
                );
            }

            if(collectionPrice.highest_price == null && collectionPrice.lowest_price == null) {
                filterParent.closest('.athena-search-filter').remove();
            }

            if(collectionPrice.highest_price === 0 && collectionPrice.lowest_price === 0) {
                filterParent.closest('.athena-search-filter').remove();
            }

            if(collectionPrice.highest_price === collectionPrice.lowest_price) {
                filterParent.closest('.athena-search-filter').remove();
            }

        }

        const filterMask = document.querySelector('.filter-mask');
        const filterBtnClose = document.querySelector('.close-filters-btn');

        filterMask?.addEventListener('click', ()=>{
            document.getElementsByTagName('body')[0]?.classList.remove('athena-search-filter-open');
        });

        filterBtnClose?.addEventListener('click', ()=>{
            document.getElementsByTagName('body')[0]?.classList.remove('athena-search-filter-open');
        });
    });
}

/**
 * Handle Append Filters
 *
 * @param filters
 * @param activeFilters
 * @param collectionPrice
 */
function appendSearchFilters(
    filters,
    activeFilters,
    collectionPrice
) {
    if(filters.length > 0) {
        document.querySelector('#athena-main-container')?.classList.remove('no-serach-filter');
        //Appending Filter Header
        athenaConfigOptions.searchSidebar.prepend(
            handleHtml(`
                <div class="athena-filter-title-main">
                    <p>Filters</p>
                    <span class="close-filters-btn"></span>
                </div>
            `, '.athena-filter-title-main')
        );

        //Appending Sidebar Filters
        appendSidebarFilters(
            filters,
            activeFilters,
            collectionPrice
        );

    } else {
        document.querySelector('#athena-main-container')?.classList.add('no-serach-filter');
        return '';
    }
}

//Exporting
export {
    appendSearchFilters
}