import EventBus from '../../Events/EventBus.js';
import Events from '../../Events/Events.js';
import MobileFiltersUI from './MobileFiltersUI.js';

class ClearFiltersButton {
    constructor() {
        this._eventBus = EventBus.getInstance();
        this._desktopButton = null;
        this._mobileButton = null;
        this._filterCountBadges = [];
        this._currentFilterCount = 0;

        this._init();
    }

    _init() {
        this._desktopButton = document.querySelector('.fuse-clear-all-filters');
        this._mobileButton = document.querySelector('.fuse-clear-filters-popup-btn');
        this._filterCountBadges = document.querySelectorAll('.fuse-filters-count');

        this._attachEventListeners();
        this._updateButtonVisibility();
    }

    _attachEventListeners() {
        // Handle desktop clear button click
        if (this._desktopButton) {
            this._desktopButton.addEventListener('click', (e) => {
                e.preventDefault();
                this._clearAllFilters();
            });
        }

        // Handle mobile clear button click
        if (this._mobileButton) {
            this._mobileButton.addEventListener('click', (e) => {
                e.preventDefault();
                this._clearAllFilters();
            });
        }

        // Listen to PRODUCTS_FILTERED event from FilterManager to update count
        this._eventBus.registerDynamicEvent({
            key: Events.PRODUCTS_FILTERED,
            callback: (data) => this._updateFilterCount(data.filters)
        });
        
    }

    _clearAllFilters() {
        // Trigger the FILTERS_CLEARED event - FilterManager will handle the rest
        this._eventBus.triggerEvent(Events.FILTERS_CLEARED);

        // Smooth scroll to the top of fusecommerce-products
        
        const productsContainer = document.querySelector('.fusecommerce-products');
        if (productsContainer) {
            const targetPosition = jQuery(productsContainer).offset().top - 100;
            jQuery('html, body').animate({
                scrollTop: targetPosition
            }, 1000, 'swing');
        }
    }

    _updateFilterCount(filters) {
        // Calculate filter count from FilterManager's active filters state
        let count = 0;

        // Count selected categories
        if (filters.categories && Array.isArray(filters.categories)) {
            count += filters.categories.length;
        }

        // Count selected tags
        if (filters.tags && Array.isArray(filters.tags)) {
            count += filters.tags.length;
        }

        // Count selected attributes (sum of all attribute values across all attribute types)
        if (filters.attributes && typeof filters.attributes === 'object') {
            count += Object.values(filters.attributes).reduce((sum, attributeValues) => {
                return sum + (Array.isArray(attributeValues) ? attributeValues.length : 0);
            }, 0);
        }

        // Check if price range is set
        if (filters.priceRange) {
            count += 1;
        }

        // Check if search query is set
        if (filters.query && filters.query.trim() !== '') {
            count += 1;
        }

        this._currentFilterCount = count;
        this._updateFilterCountBadges();
        this._updateButtonVisibility();
    }

    _updateFilterCountBadges() {
        // Update all filter count badges
        this._filterCountBadges.forEach(badge => {
            if (this._currentFilterCount > 0) {
                badge.textContent = this._currentFilterCount;
                badge.classList.remove('hidden');
            } else {
                badge.textContent = '';
                badge.classList.add('hidden');
            }
        });
    }

    _updateButtonVisibility() {
        // Show/hide clear button based on filter count
        const isMobile = MobileFiltersUI.getInstance().isMobileFilters();
        if (!isMobile) {
            if (this._desktopButton) {
                if (this._currentFilterCount > 0) {
                    this._desktopButton.classList.remove('hidden');
                    this._desktopButton.classList.add('md:block');
                } else {
                    this._desktopButton.classList.add('hidden');
                    this._desktopButton.classList.remove('md:block');
                }
            }
        } else {
            if (this._mobileButton) {
                if (this._currentFilterCount > 0) {
                    this._mobileButton.classList.remove('hidden');
                    this._mobileButton.disabled = false;
                } else {
                    this._mobileButton.classList.add('hidden');
                    this._mobileButton.disabled = true;
                }
            }
        }
    }
}

export default ClearFiltersButton;
