import EventBus from '../../Events/EventBus';
import { Events } from '../../Events/Events';

/**
 * SearchFilter Component
 *
 * Handles free text search for products by name and short_description.
 * Features:
 * - Configurable debounce delay (default 2000ms)
 * - Clear button (X icon)
 * - URL state restoration
 * - Clear filters support
 */
class SearchFilter {
    constructor() {
        this._$searchInput = null;
        this._$clearButton = null;
        this._debounceTimer = null;
        this._debounceDelay = 2000; // Default 2 seconds
        this._currentQuery = '';
        this._eventBus = EventBus.getInstance();
    }

    init() {
        this._$searchInput = jQuery('.fuse-search-filter-input');

        if (this._$searchInput.length === 0) {
            return;
        }

        this._$clearButton = this._$searchInput.siblings('.fuse-search-clear-btn');

        // Read configurable debounce delay from data attribute
        const configuredDelay = this._$searchInput.data('debounce-delay');
        if (configuredDelay && !isNaN(configuredDelay)) {
            this._debounceDelay = parseInt(configuredDelay, 10);
        }

        this._attachEventHandlers();
        this._listenForURLRestore();
        this._listenForClearFilters();
    }

    _attachEventHandlers() {
        // Handle input changes with debounce
        this._$searchInput.on('input', (e) => {
            const query = e.target.value.trim();
            this._handleSearchInput(query);
            this._updateClearButtonVisibility(query);
        });

        // Handle Enter key (immediate search, bypass debounce)
        this._$searchInput.on('keypress', (e) => {
            if (e.which === 13) { // Enter key
                e.preventDefault();
                this._clearDebounceTimer();
                const query = this._$searchInput.val().trim();
                this._triggerSearchEvent(query);
            }
        });

        // Handle clear button click
        this._$clearButton.on('click', () => {
            this._clearSearch();
        });
    }

    _handleSearchInput(query) {
        // Clear existing timer
        this._clearDebounceTimer();

        // If query is empty and we had a previous query, trigger immediately (no debounce)
        // This provides instant feedback when user clears the search
        if (query === '' && this._currentQuery !== '') {
            this._triggerSearchEvent(query);
            return;
        }

        // Set new timer for non-empty queries
        this._debounceTimer = setTimeout(() => {
            this._triggerSearchEvent(query);
        }, this._debounceDelay);
    }

    _triggerSearchEvent(query) {
        // Only trigger if query has changed
        if (query === this._currentQuery) {
            return;
        }

        this._currentQuery = query;

        this._eventBus.triggerEvent(Events.SEARCH_QUERY_CHANGED, {
            query: query
        });
    }

    _clearSearch() {
        this._clearDebounceTimer();
        this._$searchInput.val('');
        this._updateClearButtonVisibility('');
        this._triggerSearchEvent('');  // Trigger BEFORE resetting _currentQuery
        this._$searchInput.focus();
    }

    _updateClearButtonVisibility(query) {
        if (query && query.length > 0) {
            this._$clearButton.removeClass('hidden').addClass('flex');
        } else {
            this._$clearButton.removeClass('flex').addClass('hidden');
        }
    }

    _clearDebounceTimer() {
        if (this._debounceTimer) {
            clearTimeout(this._debounceTimer);
            this._debounceTimer = null;
        }
    }

    _listenForURLRestore() {
        this._eventBus.registerDynamicEvent({
            key: Events.FILTERS_RESTORED_FROM_URL,
            callback: (filters) => {
                if (filters && filters.query) {
                    this._restoreSearchFromURL(filters.query);
                }
            }
        });
    }

    _restoreSearchFromURL(query) {
        this._currentQuery = query;
        this._$searchInput.val(query);
        this._updateClearButtonVisibility(query);
    }

    _listenForClearFilters() {
        this._eventBus.registerDynamicEvent({
            key: Events.FILTERS_CLEARED,
            callback: () => {
                this._clearSearchUI();
            }
        });
    }

    _clearSearchUI() {
        this._clearDebounceTimer();
        this._$searchInput.val('');
        this._currentQuery = '';
        this._updateClearButtonVisibility('');
    }
}

export default SearchFilter;
