class IndexProducts {

    _isIndexing = false;
    _statusPollInterval = null;
    _labels = {};
    _firstLoad = true;

    init() {
        if (!jQuery('#btn-index-products')[0]) {
            return;
        }

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

    _handleEvents() {
        const _this = this;

        // Index Products button
        jQuery('#btn-index-products').on('click', function(event) {
            event.preventDefault();
            _this._triggerIndexProducts();
        });

        // Reset button
        jQuery('#btn-reset-index').on('click', function(event) {
            event.preventDefault();
            if (confirm(_this._labels.confirmReset || 'Are you sure you want to reset the indexing process? This will delete any work in progress.')) {
                _this._resetIndexing();
            }
        });

        // Refresh Status button
        jQuery('#btn-refresh-status').on('click', function(event) {
            event.preventDefault();
            _this._loadStatus();
        });
    }

    _loadStatus() {
        const _this = this;
        const ajaxPayload = {
            action: 'fuse_comm_get_index_status',
            nonce: window.FUSE_COM_ADMIN_SETTINGS?.nonce || ''
        };

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

                    // Start polling if status is 'working'
                    if (response.data.status === 'working') {
                        _this._startStatusPolling();
                    } else {
                        if (!_this._firstLoad) {
                            _this._showSuccess(_this._labels.indexingComplete || 'Unknown');
                        }
                        _this._stopStatusPolling();
                    }
                }
                _this._firstLoad = false;
            },
            error: function(xhr, status, error) {
                console.error('Error loading status:', error);
                _this._showError(_this._labels.failedToLoad || 'Failed to load indexing status');
            }
        });
    }

    _updateStatusDisplay(data) {
        const container = jQuery('#indexing-status-container');
        let html = '';

        if (data.status === 'idle') {
            html = '<div class="alert alert-info">';
            html += '<strong>' + (this._labels.labelStatus || 'Status:') + '</strong> ' + (this._labels.statusNoProcess || 'No indexing process running');
            if (data.has_index) {
                html += '<br><small class="text-muted">' + (this._labels.statusLastIndex || 'Last index was generated previously') + '</small>';
            }
            html += '</div>';
        } else if (data.status === 'working') {
            const progress = data.progress || 0;
            const phaseName = data.phase === 'taxonomies' ? (this._labels.phaseCategories || 'Categories & Attributes') : (this._labels.phaseProducts || 'Products');
            const productsLabel = this._labels.products || 'products';
            html = '<div class="alert alert-warning">';
            html += '<strong>' + (this._labels.labelStatus || 'Status:') + '</strong> ' + (this._labels.statusInProgress || 'Indexing in progress');
            html += '<br><strong>' + (this._labels.labelPhase || 'Phase:') + '</strong> ' + phaseName;
            html += '<br><strong>' + (this._labels.labelProgress || 'Progress:') + '</strong> ' + data.processed + ' / ' + data.total_products + ' ' + productsLabel + ' (' + progress.toFixed(2) + '%)';
            html += '<div class="progress mt-2" style="height: 20px;">';
            html += '<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: ' + progress + '%">' + progress.toFixed(0) + '%</div>';
            html += '</div>';

            if (data.is_stale) {
                html += '<br><small class="text-danger">' + (this._labels.warningStale || 'Warning: Process appears stale (no updates for over 1 hour)') + '</small>';
            }
            html += '</div>';
        } else if (data.status === 'completed') {
            html = '<div class="alert alert-success">';
            html += '<strong>' + (this._labels.labelStatus || 'Status:') + '</strong> ' + (this._labels.statusCompleted || 'Indexing completed successfully');
            html += '<br><strong>' + (this._labels.labelTotalProducts || 'Total Products:') + '</strong> ' + data.processed;
            html += '<br><small class="text-muted">' + (this._labels.labelStarted || 'Started:') + ' ' + this._formatTimestamp(data.started_at) + '</small>';
            html += '<br><small class="text-muted">' + (this._labels.labelCompleted || 'Completed:') + ' ' + this._formatTimestamp(data.updated_at) + '</small>';
            html += '</div>';
        } else if (data.status === 'error') {
            html = '<div class="alert alert-danger">';
            html += '<strong>' + (this._labels.labelStatus || 'Status:') + '</strong> ' + (this._labels.statusError || 'Error occurred during indexing');
            if (data.errors && data.errors.length > 0) {
                html += '<br><strong>' + (this._labels.labelErrors || 'Errors:') + '</strong>';
                html += '<ul class="mb-0">';
                data.errors.forEach(function(error) {
                    html += '<li>' + error.message + '</li>';
                });
                html += '</ul>';
            }
            html += '</div>';
        }

        container.html(html);

        // Show/hide file links
        if (data.product_url || data.category_url || data.attribute_url || data.tag_url) {
            jQuery('#indexing-files-container').show();

            if (data.product_url) {
                const productLabel = (this._labels.productsJson || 'Products JSON') + (data.product_size ? ' (' + data.product_size + ')' : '');
                jQuery('#file-products').show().find('.file-label').text(productLabel);
                jQuery('#file-products').find('a').attr('href', data.product_url);
            }
            if (data.category_url) {
                const categoryLabel = (this._labels.categoriesJson || 'Categories JSON') + (data.category_size ? ' (' + data.category_size + ')' : '');
                jQuery('#file-categories').show().find('.file-label').text(categoryLabel);
                jQuery('#file-categories').find('a').attr('href', data.category_url);
            }
            if (data.attribute_url) {
                const attributeLabel = (this._labels.attributesJson || 'Attributes JSON') + (data.attribute_size ? ' (' + data.attribute_size + ')' : '');
                jQuery('#file-attributes').show().find('.file-label').text(attributeLabel);
                jQuery('#file-attributes').find('a').attr('href', data.attribute_url);
            }
            if (data.tag_url) {
                const tagLabel = (this._labels.tagsJson || 'Tags JSON') + (data.tag_size ? ' (' + data.tag_size + ')' : '');
                jQuery('#file-tags').show().find('.file-label').text(tagLabel);
                jQuery('#file-tags').find('a').attr('href', data.tag_url);
            }
        } else {
            jQuery('#indexing-files-container').hide();
        }
    }

    _formatTimestamp(timestamp) {
        const date = new Date(timestamp * 1000);
        return date.toLocaleString();
    }

    _triggerIndexProducts() {
        if (this._isIndexing) {
            return;
        }

        const ajaxPayload = {
            action: 'fuse_comm_index_products',
            nonce: window.FUSE_COM_ADMIN_SETTINGS?.nonce || ''
        };

        this._setIndexing(true);

        setTimeout(() => {
            _this._loadStatus();
        }, 2000)

        const _this = this;
        _this._showSuccess(_this._labels.indexingStarted || 'Indexing started successfully');

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

                if (response.success) {
                    _this._showSuccess(_this._labels.indexingStarted || 'Indexing started successfully');
                    _this._loadStatus();
                } else {
                    _this._showError(response.data?.message || _this._labels.failedToStart || 'Failed to start indexing');
                }
            },
            error: function(xhr, status, error) {
                _this._setIndexing(false);
                _this._showError((_this._labels.errorStarting || 'Error starting indexing') + ': ' + error);
            }
        });
    }

    _resetIndexing() {
        const ajaxPayload = {
            action: 'fuse_comm_reset_index',
            nonce: window.FUSE_COM_ADMIN_SETTINGS?.nonce || ''
        };

        const _this = this;
        jQuery.ajax({
            url: window.FUSE_COM_ADMIN_SETTINGS?.ajax_url || ajaxurl,
            type: 'POST',
            data: ajaxPayload,
            success: function(response) {
                if (response.success) {
                    _this._showSuccess(_this._labels.indexingReset || 'Indexing process reset successfully');
                    _this._loadStatus();
                    _this._triggerIndexProducts();
                } else {
                    _this._showError(response.data?.message || _this._labels.failedToReset || 'Failed to reset indexing');
                }
            },
            error: function(xhr, status, error) {
                _this._showError((_this._labels.errorResetting || 'Error resetting indexing') + ': ' + error);
            }
        });
    }

    _startStatusPolling() {
        const _this = this;

        // Clear existing interval
        this._stopStatusPolling();
        // Poll every 2 seconds
        this._statusPollInterval = setInterval(function() {
            _this._loadStatus();
        }, 2000);
    }

    _stopStatusPolling() {
        if (this._statusPollInterval) {
            clearInterval(this._statusPollInterval);
            this._statusPollInterval = null;
        }
    }

    _setIndexing(val) {
        this._isIndexing = val;
        if (val) {
            jQuery('#btn-index-products').addClass('disabled').prop('disabled', true);
        } else {
            jQuery('#btn-index-products').removeClass('disabled').prop('disabled', false);
        }
    }

    _showSuccess(message) {
        if (typeof toastr !== 'undefined') {
            toastr.success(message);
        } else {
            alert(message);
        }
    }

    _showError(message) {
        if (typeof toastr !== 'undefined') {
            toastr.error(message);
        } else {
            alert(message);
        }
    }
}
export default IndexProducts;