import BaseComponent from "../BaseComponent";
import EventBus from "../../Events/EventBus";
import Events from "../../Events/Events";

class CategoryFilter {
    init() {
        this._attachEventHandlers();
        this._listenForURLRestore();
        this._listenForClearFilters();
    }

    _listenForURLRestore() {
        EventBus.getInstance().registerDynamicEvent({
            key: Events.FILTERS_RESTORED_FROM_URL,
            callback: (filters) => this._restoreUIFromFilters(filters)
        });
    }

    _listenForClearFilters() {
        EventBus.getInstance().registerDynamicEvent({
            key: Events.FILTERS_CLEARED,
            callback: () => this._clearAllCategories()
        });
    }

    _clearAllCategories() {
        // Clear all checked categories
        jQuery('.filter-category-checkbox').removeClass('checked');
        jQuery('.checkmark').addClass('hidden');
    }

    _restoreUIFromFilters(filters) {
        // Clear all active states first
        jQuery('.filter-category-checkbox').removeClass('checked');
        jQuery('.checkmark').addClass('hidden');

        // Set active states from URL
        if (filters.categories && filters.categories.length > 0) {
            filters.categories.forEach(categoryId => {
                this._setCheckboxState(categoryId, true);
            });
        }
    }

    _attachEventHandlers() {
        const $filterContainer = jQuery('.fusecommerce-filters');
        if (!$filterContainer.length) {
            return;
        }

        // Handle checkbox and label clicks
        $filterContainer.on('click', '.filter-category-checkbox, .filter-category-label', (e) => {
            e.preventDefault();
            const $target = jQuery(e.currentTarget);
            const categoryId = $target.data('category-id');
            const categorySlug = $target.data('category-slug');
            const childIds = $target.data('child-ids') || [];
            const isParent = $target.data('is-parent') === 'true' || $target.data('is-parent') === true;
            const isActive = this._isCheckboxActive(categoryId);

            // Toggle this category and all children if parent
            const categoriesToToggle = isParent ? [categoryId, ...childIds] : [categoryId];

            const eventBus = EventBus.getInstance();
            if (isActive) {
                // Deselect all
                categoriesToToggle.forEach(id => {
                    this._setCheckboxState(id, false);
                    const slug = this._getSlugById(id);
                    eventBus.triggerEvent(Events.CATEGORY_DESELECTED, {
                        categoryId: id,
                        categorySlug: slug
                    });
                });
            } else {
                // Select all
                categoriesToToggle.forEach(id => {
                    this._setCheckboxState(id, true);
                    const slug = this._getSlugById(id);
                    eventBus.triggerEvent(Events.CATEGORY_SELECTED, {
                        categoryId: id,
                        categorySlug: slug
                    });
                });
            }
        });

        // Handle expand/collapse toggle (arrow button)
        $filterContainer.on('click', '.category-expand-toggle', (e) => {
            e.preventDefault();
            const $button = jQuery(e.currentTarget);
            const $wrapper = $button.closest('.category-item-wrapper');
            const $children = $wrapper.find('> .category-children').first();
            const $chevron = $button.find('.chevron-icon');

            if ($children.hasClass('hidden')) {
                // Expand
                $children.removeClass('hidden');
                $chevron.addClass('rotate-90');
                $button.attr('aria-expanded', 'true');
            } else {
                // Collapse
                $children.addClass('hidden');
                $chevron.removeClass('rotate-90');
                $button.attr('aria-expanded', 'false');
            }
        });

        // Handle "Show All Categories" button
        $filterContainer.on('click', '.category-show-all-btn', (e) => {
            e.preventDefault();
            jQuery('.category-item-wrapper.hidden-initially').removeClass('hidden-initially');
            jQuery('.category-show-all-btn').hide();
        });

        // Handle "clear all categories" button if exists
        $filterContainer.on('click', '.clear-category-filters', (e) => {
            e.preventDefault();
            jQuery('.filter-category-checkbox.checked').each((i, el) => {
                const $checkbox = jQuery(el);
                const categoryId = $checkbox.data('category-id');
                const categorySlug = $checkbox.data('category-slug');
                this._setCheckboxState(categoryId, false);
                EventBus.getInstance().triggerEvent(Events.CATEGORY_DESELECTED, { categoryId, categorySlug });
            });
        });
    }

    _isCheckboxActive(categoryId) {
        const $checkbox = jQuery(`.filter-category-checkbox[data-category-id="${categoryId}"]`);
        return $checkbox.hasClass('checked');
    }

    _setCheckboxState(categoryId, isChecked) {
        const $checkbox = jQuery(`.filter-category-checkbox[data-category-id="${categoryId}"]`);
        const $checkmark = $checkbox.find('.checkmark');

        if (isChecked) {
            $checkbox.addClass('checked');
            $checkmark.removeClass('hidden');
        } else {
            $checkbox.removeClass('checked');
            $checkmark.addClass('hidden');
        }
    }

    _getSlugById(id) {
        const $el = jQuery(`.filter-category-checkbox[data-category-id="${id}"]`);
        return $el.data('category-slug') || '';
    }
}

export default CategoryFilter;
