import { athenaConfig, athenaConfigOptions } from '../../../global/athena-config.js';
import { athenaSpinner } from '../../renderer/athena-spinner.js';
import { athenaFetchApi } from '../../../global/athena-fetch-api.js';
import { appendSearchProducts } from '../../renderer/products.js';
import { addObserverToProducts } from '../../helper/infinite-scroll/add-observer-to-products.js';
import { showPrevBtn } from '../../renderer/show-prev-btn.js';
import { getUrlSearchParams } from '../../helper/url-search-params.js';
import { appendAmount } from '../../renderer/amount.js';
import { appendSearchSorters } from '../../renderer/sorters.js';
import checkActivePage from '../helpers/format-data-object.js';
import lazyLoad from '../../../global/helpers/lazy-loading.js';
import didYouMean from "../../../global/did-you-mean/did-you-mean.js";

/**
 * Fetch Previous Data
 */
function fetchMoreDataPrev() {
    //Appending Spinner
    athenaConfigOptions.showSpinner = true;
    athenaSpinner();

    //Forming Data Object
    const data = {
        'service': 'search/data',
        'athenaUid': athenaConfigOptions.athenaUid,
        'search': 0,
        'page': athenaConfigOptions.prevPage,
        'q': athenaConfigOptions.searchQuery
    }

    if(athenaConfig.isCustomerLoyalty) {
        data['customer_group_id'] = athenaConfigOptions.customerGroupID;
    }

    //Get URL Search params and add it to data
    const queries = getUrlSearchParams();
    for (const queryKey in queries) {
        if(queryKey !== 'page') {
            data[queryKey] = queries[queryKey];
        }
    }

    const {
        isVisualSearch,
        isCategory
    } = checkActivePage(data);

    /**
     * Checking date page is not null
     * because of the prev page infinite scroll
     */
    if(data.page) {
        isVisualSearch
            .then((visual) => {
                if(athenaConfig.hybridSearchModel && !visual && !isCategory) {
                    data['hybrid_search_model_type'] = athenaConfig.hybridSearchModel;
                }

                athenaFetchApi(data, true)
                    .then(response => {
                        appendSearchProducts(
                            response.data.products.results.reverse(),
                            athenaConfigOptions.searchProductContainer, true,
                            isCategory,
                            response.data.best_match_size,
                            response.data.products.amounts,
                            false,
                            true
                        );

                        athenaConfigOptions.prevPage = response.data.products.amounts.prev_page;
                        athenaConfigOptions.currentPage = response.data.products.amounts.current_page;
                        appendAmount(response.data.products.amounts);
                        appendSearchSorters(
                            response.data.products.sorters,
                            response.data.products.results
                        );
                        //Getting products
                        const products = document.querySelectorAll('.product-item');
                        const page = response.data.products.amounts.current_page
                        //Adding Attributes to products
                        products.forEach((product)=> {
                            if(!product.getAttribute('data-page')) {
                                product.setAttribute('data-page', page);
                            }
                        });
                        //Adding observer to products
                        addObserverToProducts(page);
                        //Showing Prev Button
                        showPrevBtn();
                        // Remove spinner
                        athenaConfigOptions.showSpinner = false;
                        athenaSpinner();
                        //Lazy Loading Images
                        lazyLoad('.athena-product-image-photo');

                        //Handle Did you mean
                        didYouMean(
                            response.data?.did_you_mean,
                            document.querySelector('#athena-landing-page__container') ?? null,
                            'search'
                        );
                    });
            });
    } else {
        // Remove spinner
        athenaConfigOptions.showSpinner = false;
        athenaSpinner();
    }
}

//Exporting all Functions
export {
    fetchMoreDataPrev
}