"use strict";

interface AdminFunctions {
    toggleMenuVisibility(hideLargeMenu: boolean): void;
    addProductToCategory(productId: string): void;
    searchSuggestions(inputSelector: string): void;
    markProductAsHot(productId: string): void;
}

const AdminFunctions: AdminFunctions = (() => {

    function toggleMenuVisibility(hideLargeMenu: boolean): void {
        const contentContainer = $('#js-admin-content-container');
        const largeMenu = $('#js-menu-big');
        const smallMenu = $('#js-menu-small');
        const searchForm = $('#js-form-search');

        contentContainer.toggleClass('show-large-menu', !hideLargeMenu);
        largeMenu.toggleClass('hidden', hideLargeMenu);
        smallMenu.toggleClass('hidden', !hideLargeMenu);
        searchForm.toggleClass('menu-hide', hideLargeMenu);

        localStorage.setItem(hideLargeMenu ? 'menu_big' : 'menu_small', 'hidden');
        localStorage.removeItem(hideLargeMenu ? 'menu_small' : 'menu_big');
    }

    function debounce(func: (...args: any[]) => void, wait: number, immediate: boolean) {
        let timeout: ReturnType<typeof setTimeout> | null = null;
        return function (this: HTMLInputElement, ...args: any[]) {
            const context = this;
            const later = function () {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            const callNow = immediate && !timeout;
            if (timeout !== null) {
                clearTimeout(timeout);
            }
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    }

    function addProductToCategory(productId: string): void {
        const statusElement = $('#status_' + productId);
        statusElement.html('<span class="loading loading-bars loading-sm"></span><span class="ml-[3px]">Processing...</span>');
        setTimeout(() => {
            statusElement.html('');
        }, 1000);
    }

    function searchSuggestions(inputSelector: string): void {
        $(inputSelector).keyup(debounce(function (this: HTMLInputElement) {
            $('#js-show-search').show();
        }, 300, false) as any);

        $('body').click(function () {
            $('#js-show-search').hide();
        });
    }

    function markProductAsHot(productId: string): void {
        const statusElement = $('#js-status-hottype-' + productId);
        statusElement.html('<span class="loading loading-bars loading-sm"></span><span class="ml-[3px]">Processing...</span>');
        setTimeout(() => {
            statusElement.html('');
        }, 1000);
    }

    return {
        toggleMenuVisibility,
        addProductToCategory,
        searchSuggestions,
        markProductAsHot
    };
})();
