import { appendSearchProducts } from '../../renderer/products.js';
import { appendSearchFilters } from '../../renderer/filters.js';
import { appendSearchSorters } from '../../renderer/sorters.js';
import { appendPager } from '../../renderer/pager.js';
import { appendBreadcrumbsandCategoryName } from '../../renderer/category-name-and-breadcrumbs.js';
import { appendSearchBanners } from '../../renderer/banners.js';
import { showPrevBtn } from '../../renderer/show-prev-btn.js';
import { appendProductEnd } from '../../renderer/product-end.js';
import { athenaSpinner } from '../../renderer/athena-spinner.js';
import { handlePriceRange } from '../../helper/search/handle-price-range.js';
import { appendActiveFilters } from '../../renderer/active-filters.js';
import { filterDropdown } from '../../helper/filter-dropdown.js';
import { appendAmount } from '../../renderer/amount.js';
import { appendViewMode } from '../../renderer/view-mode.js';
import { appendProductsPerPage } from '../../renderer/products-per-page.js';
import {
    appendSearchTitleResult,
    searchResultsForVisualSimilarity
} from '../../renderer/search-title-result.js';
import {
    setUrlSearchParams,
    setUrlCategoryParams
} from '../../helper/set-url-search-params.js';
import {
    athenaConfig,
    athenaConfigOptions,
    athenaConfigDemo
} from '../../../global/athena-config.js';
import appendVisualFilters from '../../renderer/visual-filters.js';
import {
    dispatchSearchDataAnalyticsEvent,
    handleHtml,
    handleShowMoreLess
} from "../../../global/helpers/athena-global-helper.js";
import didYouMean from "../../../global/did-you-mean/did-you-mean.js";

/**
 * Add border right sidebar
 */
function addBorderRightSidebar() {
    const athenaSidebar = document.querySelector(`.athena-sidebar`);
    athenaSidebar?.classList.add('athena-border-right');
}

function handleOpenActiveFiltersSearchPage(activeFilters) {

    if(activeFilters.length){
        activeFilters.forEach(function(element){

            if(element.type.includes('category')){
                let categoryFilter = [
                    document.querySelector(`.athena-search-filter[data-filter-type="category1"]`),
                    document.querySelector(`.athena-search-filter[data-filter-type="category2"]`),
                    document.querySelector(`.athena-search-filter[data-filter-type="category3"]`),
                    document.querySelector(`.athena-search-filter[data-filter-type="category4"]`),
                    document.querySelector(`.athena-search-filter[data-filter-type="category5"]`)
                ]
                Array.from(categoryFilter).forEach(function(elementInner){
                    if(elementInner){
                        elementInner.querySelector('.athena-filter-title').classList.add('athena-filter-title-active');
                        elementInner.querySelector('.athena-filter-container').classList.add('athena-filter-container-active')
                    }
                });
            }

            if(document.querySelector(`.athena-search-filter[data-filter-type="${element.type}"]`)){
                let activeFilterContainer = document.querySelector(`.athena-search-filter[data-filter-type="${element.type}"]`);
                if(activeFilterContainer){
                    activeFilterContainer.querySelector('.athena-filter-title').classList.add('athena-filter-title-active');
                    activeFilterContainer.querySelector('.athena-filter-container').classList.add('athena-filter-container-active');
                }
            }

        });
    }
}

function numberOfActiveFilters(){
    let selectedFiltersContainer = document.querySelectorAll('.athena-filter-container-active');
    if(selectedFiltersContainer.length){
        selectedFiltersContainer.forEach(function(element){

            let selectedNumber = 0;
            let selectedFilter = element.querySelectorAll('.athena-filter-checkbox')
            if(selectedFilter.length){
                selectedFilter.forEach(function(elementInner){
                    if(elementInner.checked){
                        selectedNumber++;
                    }
                })
            }
            if(selectedNumber){
                element.closest('.athena-search-filter')?.querySelector('.athena-filter-title')?.append(
                    handleHtml(`
                        <span class="athena-active-filter-number">
                            (${selectedNumber})
                        </span>
                    `, '.athena-active-filter-number')
                );
            }
        })
    }

}

/**
 * Handle Response for Search Page
 *
 * @param response
 * @param initResponse
 * @param isVisualSearch
 * @param isCategory
 * @returns {boolean}
 */
async function handleResponseSearch(
    response,
    initResponse,
    isVisualSearch,
    isCategory
) {
    // Close filters
    document.getElementsByTagName('body')[0]?.classList.remove('athena-search-filter-open');

    if(response.data) {
        //Keyword Redirects
        if (typeof response.data.url !== 'undefined' && response.data.url !== null) {
            const redirectEvent = new CustomEvent('keyword-redirect-data', {detail: { url: response.data.url }});
            window.dispatchEvent(redirectEvent);

            if(response.data.url.length == 0){
                setTimeout(() => {
                    window.location.href = window.location.origin;
                }, 300);
                return false;
            }else{
                setTimeout(() => {
                    window.location.href = response.data.url;
                }, 300);
                return false;
            }
        }

        if(initResponse) {
            if(isCategory){
                document.body.classList.remove('search-page');
                document.body.classList.add('category-page');
            }else{
                document.body.classList.remove('category-page');
                document.body.classList.add('search-page');
            }

            if(athenaConfig.isDemo){

                let athenaStoriesCategory = document.querySelector('.athena-stories-category');
                let categoryStoryArray = athenaConfigDemo?.categoryPageStory;

                if(categoryStoryArray){
                    categoryStoryArray.forEach(function(item) {
                        if(response.data?.category_name?.toLowerCase() == item.categoryName){
                            athenaStoriesCategory?.classList.add('active');

                            athenaStoriesCategory.append(
                                handleHtml(`
                                        <div class="athena-story-item" data-recommender-id="${item.recommenderId}" data-recommender-sku="${item.recommenderSku}">
                                            <div class="athena-story-item-img">
                                                <img class="story-image" src="${item.image}" alt="Athena story">
                                            </div>
                                            <p class="athena-story-title">${item.title}</p>
                                        </div>
                                    `, '.athena-story-item')
                            );

                        }
                    });
                }

            }

            appendSearchTitleResult(isVisualSearch ? 'image' : response.data.query, !isCategory);
            //Check if there is banner in response
            if(response.data.banner) appendSearchBanners(response.data.banner);
        }


        if(!isVisualSearch && !isCategory) {
            let res = response.data.query?.replace('<>', '');
            athenaConfigOptions.searchForClickProduct += res + ',';
            athenaConfigOptions.searchQuery = response.data.query;
        }

        if (typeof response.data.products !== 'undefined' && response.data.products !== null) {
            if(!initResponse) {
                athenaConfigOptions.searchProductContainer.innerHTML = '';
                athenaConfigOptions.searchSidebar.innerHTML = '';
                if(document.querySelector('.product-items-cutoff')){
                    document.querySelector('.product-items-cutoff').innerHTML = '';
                }

                const bestMatches = document.querySelector('.best-matches-div');
                if(bestMatches) {
                    bestMatches.style.display = 'none';
                }

                const alsoRelevant = document.querySelector('.also-relevant-div');
                if(alsoRelevant) {
                    alsoRelevant.style.display = 'none';
                }
            }

            // Append Products, Filters and Sorters
            await searchResultsForVisualSimilarity();
            appendViewMode(response.data.modes, response.data.products.results);
            appendSearchProducts(
                response.data.products.results,
                athenaConfigOptions.searchProductContainer,
                null,
                isCategory,
                response.data.best_match_size,
                response.data.products.amounts
            );
            appendSearchFilters(response.data.products.filters, response.data.products.active_filters, response.data.products.collection_price);
            appendActiveFilters(response.data.products.active_filters, response.data.products.sorters);
            appendAmount(response.data.products.amounts);
            appendProductEnd(response.data.products.amounts.current_page, response.data.products.amounts.last_page);
            appendSearchSorters(response.data.products.sorters, response.data.products.results);
            appendPager(response.data.products.pager);
            appendProductsPerPage(response.data.products.orders);
            //Appending Visual Filters if its Category Response
            if(isCategory) appendVisualFilters(response.data.products.visual_filter);
            appendBreadcrumbsandCategoryName(response.data.breadcrumbs, response.data.category_name, isCategory);

            // Next, prev, current and last page for Infinite Scroll
            athenaConfigOptions.nextPage = response.data.products.amounts.next_page;
            athenaConfigOptions.prevPage = response.data.products.amounts.prev_page;
            athenaConfigOptions.currentPage = response.data.products.amounts.current_page;
            athenaConfigOptions.lastPage = response.data.products.amounts.last_page;

            handleOpenActiveFiltersSearchPage(response.data.products.active_filters);

            numberOfActiveFilters();

            // Set URL
            if(!initResponse) {
                !isCategory ?
                    setUrlSearchParams(response.data.current_path, athenaConfig.pagerStatus) :
                    setUrlCategoryParams(response.data.current_path);
            }
        }

        //Handle Did you mean
        didYouMean(
            response.data?.did_you_mean,
            document.querySelector('#athena-landing-page__container') ?? null,
            'search'
        );

        // Append Prev button
        showPrevBtn();

        // Price Filter
        handlePriceRange();

        // Handle Show More
        handleShowMoreLess(
            '.athena-filter-container',
            '.athena-cutoff__container-filters-landing',
            'search'
        );

        // Remove spinner
        athenaConfigOptions.showSpinner = false;
        athenaSpinner();

        // Dropdown Filters
        if(response.data.products.filters.length > 0) {
            filterDropdown();
        }

        addBorderRightSidebar();

        window.setTimeout(() =>{
            athenaConfigOptions.scrollStatus = true;

            window.dispatchEvent(athenaConfigOptions.searchDataFetchedEvent);

            dispatchSearchDataAnalyticsEvent(
                isVisualSearch,
                isCategory
            );
        }, 500);

        if (window.innerWidth <= 767) {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }



    } else {
        throw new Error('Please check Athena Search connection!');
    }
}

export {
    handleResponseSearch
}