import { athenaConfig, athenaConfigOptions } from '../../global/athena-config.js';
import { athenaFetchApi } from '../../global/athena-fetch-api.js';
import { handleResponseData } from '../renderer/autocomplete-response.js';
import { handleMobileLayoutThree } from '../renderer/autocomplete-l3-mobile-response.js';
import { handleResponseDataLayoutThree } from '../renderer/autocomplete-l3-response.js';
import {
    refreshElements,
    addLoaderAutocomplete,
    removeLoaderAutocomplete
} from '../../global/helpers/athena-global-helper.js';
import {
    changeAutocompletePosition,
    showNoResult,
    hideNoResult,
    showAutocompleteBox,
    hideAutocompleteBox,
    trueAutocompleteUpperLowerCaseSet,
    removeCloseButton
} from '../helper/ajax-helper.js';

/**
 * Fetch First Click Data Function
 *
 * @param noItems
 */
function fetchFirstClick(noItems = false) {
    if(athenaConfigOptions.allowFetchFirstClick) {

        const data = {
            'service': 'autocomplete/first-click',
            'athenaUid': athenaConfigOptions.athenaUid,
        }

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

        athenaFetchApi(data, true)
            .then(response => {
                refreshElements();
                handleResponseData(response.data, 'first-click');
                //Check if there are no items and show first click with or without message
                noItems ? showAutocompleteBox() : afterSearchResultCheck(null);

                athenaConfigOptions.allowFetchFirstClick = false;
                athenaConfigOptions.firstClickDataObject = response.data;
                localStorage.setItem('firstClickDataObject', JSON.stringify(response.data));

                const firstClickEvent = new CustomEvent("first-click-data", { detail: response.data });
                window.dispatchEvent(firstClickEvent);

                //Changing Autocomplete Position Based on the API
                changeAutocompletePosition('first-click');
                //Removing Loader
                removeLoaderAutocomplete();

            });
    } else {
        refreshElements();
        handleResponseData(athenaConfigOptions.firstClickDataObject, 'first-click');
        const firstClickEvent = new CustomEvent("first-click-data", { detail: athenaConfigOptions.firstClickDataObject });
        window.dispatchEvent(firstClickEvent);
        //Check if there are no items and show first click with or without message
        noItems ? showAutocompleteBox() : afterSearchResultCheck(null);
        //Changing Autocomplete Position Based on the API
        changeAutocompletePosition('first-click');
        //Removing Loader
        removeLoaderAutocomplete();
    }
}

/**
 * Rechecking Search Value
 * Because Layout Three Response is slow and
 * toggles Autocomplete After First Click
 * even tho search value is empty
 *
 *
 * @returns {boolean}
 */
function recheckSearchValue() {
    return document.querySelector('#search').value !== '';
}

/**
 * Remove True Autocomplete
 */
function removeTrueAutocomplete() {
    athenaConfigOptions.searchForm.removeAttribute('true-autocomplete-text');
}

/**
 * Fetch Autocomplete Data Function
 *
 * @param value
 */
function fetchAutocomplete(value) {
    if(value.trim() === '') {
        return;
    }
    const productInfoAutocompleteElement = document.querySelector('#product-info-sidebar-autocomplete');
    productInfoAutocompleteElement?.classList.remove('product-info-sidebar-autocomplete-active');
    //Add Loader
    addLoaderAutocomplete();
    //Replace input
    let res = value.replace('<>', '');
    athenaConfigOptions.searchForClickProduct += res + ',';

    //Forming Data Object
    const data = {
        'service': athenaConfig.layoutType === 'athena-l3' ? 'search/autocomplete' : 'autocomplete',
        'athenaUid': athenaConfigOptions.athenaUid,
        'q': value.trim()
    }

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

    if(athenaConfig.hybridSearchModel) {
        data['hybrid_search_model_type'] = athenaConfig.hybridSearchModel;
    }

    //Adding Search Tab into data based on the layout type
    const searchTab = document.querySelector('.athena-tabs-radio:checked')?.value;
    athenaConfig.layoutType !== 'athena-l3' && typeof searchTab !== 'undefined' && searchTab ? data['autocomplete_tab'] = searchTab : '';

    athenaFetchApi(data, true)
        .then(response => {
            //Rechecking if search value is not empty
            if(recheckSearchValue()) {
                //Changing Autocomplete Position Based on the API
                changeAutocompletePosition('autocomplete');
                //Refresh Elements
                refreshElements();
                //Remove True Autocomplete
                removeTrueAutocomplete();
                //Handle Response based on the layout type
                athenaConfig.layoutType === 'athena-l3' ?
                    handleResponseDataLayoutThree(response) :
                    handleResponseData(response.data, 'autocomplete');
                afterSearchResultCheck(value);
                trueAutocompleteUpperLowerCaseSet(value);
                //Handle Mobile display for layout three
                if(athenaConfig.layoutType === 'athena-l3') handleMobileLayoutThree();

                const overlayBackground = document.querySelector('.overlay-background');
                if(overlayBackground) {
                    if(!overlayBackground?.classList.contains('background-overlay')) overlayBackground?.classList.add('background-overlay');
                }

                const autocompleteEvent = new CustomEvent("autocomplete-data", { detail: response.data });
                window.dispatchEvent(autocompleteEvent);
            }
            //Remove Loader Autocomplete
            removeLoaderAutocomplete();
        });
}

/**
 * After Search Results Check Function
 *
 * @param value
 */
function afterSearchResultCheck(value) {
    if(athenaConfigOptions.showNoItemsMessage) {
        fetchFirstClick(true);
        showNoResult(value);
    } else {
        hideNoResult();
        showAutocompleteBox();
    }
}

/**
 * Fetch Search Tabs
 */
function fetchSearchTabs() {
    const data = {
        'service': 'search-tabs',
        'athenaUid': athenaConfigOptions.athenaUid,
    }

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

    athenaFetchApi(data)
        .then(response => {
            athenaConfigOptions.searchTabsDataObject = response.data;
        });
}

//Exports
export {
    fetchFirstClick,
    fetchAutocomplete,
    fetchSearchTabs,
    hideAutocompleteBox,
    removeCloseButton
}
