class FilterOrdering {

    _config = [];
    _labels = {};
    _isLoading = false;

    init() {
        console.log('Init filter ordering');
        if (!jQuery('#filter-ordering-list')[0]) {
            return;
        }

        this._labels = window.FUSE_COM_ADMIN_SETTINGS?.labels || {};
        this._handleEvents();
        this._loadConfiguration();
    }

    _handleEvents() {
        const _this = this;

        // Refresh from Index button
        jQuery('#btn-refresh-filters').on('click', function(event) {
            event.preventDefault();

            // Show confirmation if there are unsaved changes
            if (_this._hasUnsavedChanges()) {
                if (!confirm(_this._labels.confirmRefresh || 'This will reload the configuration from index data. Any unsaved changes will be lost. Continue?')) {
                    return;
                }
            }

            _this._loadConfiguration(true);
        });

        // Checkbox change events (delegated)
        jQuery('#filter-ordering-list').on('change', '.filter-visibility-checkbox', function() {
            _this._updateConfiguration();
        });

        // Prevent form submission on enter in the list
        jQuery('#filter-ordering-list').on('keypress', function(e) {
            if (e.which === 13) {
                e.preventDefault();
            }
        });
    }

    _loadConfiguration(refresh = false) {
        const _this = this;

        if (_this._isLoading) {
            return;
        }

        _this._setLoading(true);

        const ajaxPayload = {
            action: 'fuse_comm_load_filter_config',
            nonce: window.FUSE_COM_ADMIN_SETTINGS?.nonce || '',
            refresh: refresh ? 'true' : 'false'
        };

        jQuery.ajax({
            url: window.FUSE_COM_ADMIN_SETTINGS?.ajax_url || ajaxurl,
            type: 'POST',
            data: ajaxPayload,
            success: function(response) {
                _this._setLoading(false);

                if (response.success && response.data) {
                    _this._config = response.data.config || [];
                    _this._renderList();

                    // Show warning if no indexing data
                    if (!response.data.hasIndexingData) {
                        _this._showWarning(_this._labels.noIndexData || 'Please run indexing first to configure filters.');
                    } else if (refresh) {
                        _this._showSuccess(response.data.message || _this._labels.configRefreshed || 'Configuration refreshed from index data');
                    }
                } else {
                    _this._showError(response.data?.message || _this._labels.failedToLoad || 'Failed to load filter configuration');
                    _this._showEmptyState();
                }
            },
            error: function(xhr, status, error) {
                _this._setLoading(false);
                console.error('Error loading configuration:', error);
                _this._showError(_this._labels.errorLoading || 'Error loading filter configuration');
                _this._showEmptyState();
            }
        });
    }

    _renderList() {
        const list = jQuery('#filter-ordering-list');
        list.empty();

        if (!this._config || this._config.length === 0) {
            this._showEmptyState();
            return;
        }

        // Hide empty state, show container
        jQuery('#filter-empty-state').hide();
        jQuery('#filter-ordering-container').show();

        // Render each filter item
        this._config.forEach((filter, index) => {
            const item = this._createFilterItem(filter, index);
            list.append(item);
        });

        // Initialize jQuery UI Sortable
        this._initializeSortable();

        // Update hidden input
        this._updateConfiguration();
    }

    _createFilterItem(filter, index) {
        const typeBadgeColor = this._getTypeBadgeColor(filter.type);
        const typeLabel = this._getTypeLabel(filter.type);

        const html = `
            <li class="list-group-item filter-item" data-id="${filter.id}" data-type="${filter.type}" data-order="${filter.order}">
                <div class="d-flex align-items-center">
                    <span class="filter-drag-handle" title="Drag to reorder">⋮⋮</span>
                    <span class="badge ${typeBadgeColor} filter-type-badge">${typeLabel}</span>
                    <span class="filter-label">${this._escapeHtml(filter.label)}</span>
                    <div class="filter-visibility-toggle form-check ms-3">
                        <input class="form-check-input filter-visibility-checkbox"
                               type="checkbox"
                               id="filter-visible-${filter.id}"
                               ${filter.visible ? 'checked' : ''}>
                        <label class="form-check-label" for="filter-visible-${filter.id}">
                            ${this._labels.showInFrontend || 'Show in Frontend'}
                        </label>
                    </div>
                </div>
            </li>
        `;

        return jQuery(html);
    }

    _initializeSortable() {
        const _this = this;

        jQuery('#filter-ordering-list').sortable({
            handle: '.filter-drag-handle',
            placeholder: 'ui-sortable-placeholder list-group-item',
            forcePlaceholderSize: true,
            update: function(event, ui) {
                // Update configuration after drag
                _this._updateConfiguration();
            },
            start: function(event, ui) {
                ui.placeholder.height(ui.item.height());
            }
        });
    }

    _updateConfiguration() {
        const _this = this;
        const newConfig = [];

        // Read current state from DOM
        jQuery('#filter-ordering-list .filter-item').each(function(index) {
            const $item = jQuery(this);
            const id = $item.data('id');
            const type = $item.data('type');
            const label = $item.find('.filter-label').text();
            const visible = $item.find('.filter-visibility-checkbox').is(':checked');

            newConfig.push({
                id: id,
                type: type,
                label: label,
                visible: visible,
                order: index
            });
        });

        // Update internal config
        this._config = newConfig;

        // Update hidden input for form submission
        jQuery('#filter-components-data').val(JSON.stringify(newConfig));
    }

    _setLoading(isLoading) {
        this._isLoading = isLoading;

        if (isLoading) {
            jQuery('#filter-loading-state').show();
            jQuery('#filter-ordering-container').hide();
            jQuery('#filter-empty-state').hide();
            jQuery('#btn-refresh-filters').prop('disabled', true);
        } else {
            jQuery('#filter-loading-state').hide();
            jQuery('#btn-refresh-filters').prop('disabled', false);
        }
    }

    _showEmptyState() {
        jQuery('#filter-ordering-container').hide();
        jQuery('#filter-empty-state').show();
    }

    _getTypeBadgeColor(type) {
        switch(type) {
            case 'search':
                return 'bg-dark';
            case 'category':
                return 'bg-primary';
            case 'tag':
                return 'bg-warning';
            case 'attribute':
                return 'bg-info';
            case 'price':
                return 'bg-success';
            default:
                return 'bg-secondary';
        }
    }

    _getTypeLabel(type) {
        switch(type) {
            case 'search':
                return this._labels.typeSearch || 'Search';
            case 'category':
                return this._labels.typeCategory || 'Category';
            case 'tag':
                return this._labels.typeTag || 'Tag';
            case 'attribute':
                return this._labels.typeAttribute || 'Attribute';
            case 'price':
                return this._labels.typePrice || 'Price';
            default:
                return type;
        }
    }

    _escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    _hasUnsavedChanges() {
        // Check if the hidden input has a value (configuration loaded)
        const savedData = jQuery('#filter-components-data').val();
        return savedData && savedData.length > 0;
    }

    _showSuccess(message) {
        if (typeof toastr !== 'undefined') {
            toastr.success(message);
        } else {
            console.log('Success:', message);
        }
    }

    _showError(message) {
        if (typeof toastr !== 'undefined') {
            toastr.error(message);
        } else {
            console.error('Error:', message);
            alert(message);
        }
    }

    _showWarning(message) {
        if (typeof toastr !== 'undefined') {
            toastr.warning(message);
        } else {
            console.warn('Warning:', message);
        }
    }
}

export default FilterOrdering;
