class MostPopularLinks {
    constructor(dateRangeSelector, linkSelector) {
        // Import WordPress i18n function
        this.__ = wp.i18n.__;
        
        // Initialize pagination variables
        this.currentPage = 1;
        this.totalPages = 1;
        this.totalItems = 0;
        this.itemsPerPage = null; // Will be set from AJAX response
        this.trackUniqueVisitors = linkcentral_insights_data.track_unique_visitors === '1';
        this.dateRangeSelector = dateRangeSelector;
        this.linkSelector = linkSelector;
        this.selectedLinkId = null;
        this.selectedCategoryId = null;
    }

    init() {
        // Add loading overlay immediately
        this.addLoadingOverlay();
        
        // Listen for date range changes from the shared selector
        this.dateRangeSelector.addEventListener((dateRange) => {
            this.handleDateRangeChange(dateRange);
        });
        
        // Listen for link/category selection changes from the shared selector
        if (this.linkSelector) {
            this.linkSelector.addEventListener((selection) => {
                this.handleSelectionChange(selection);
            });
        }
        
        // Set up event listeners for user interactions
        this.setupEventListeners();
    }

    addLoadingOverlay() {
        const $table = jQuery('#linkcentral-top-links-table');
        
        // Add overlay if it doesn't exist yet
        if ($table.find('.linkcentral-loading-overlay').length === 0) {
            $table.css('position', 'relative');
            $table.append(`
                <div class="linkcentral-loading-overlay" style="display: none;">
                    <span class="spinner is-active"></span>
                </div>
            `);
        } else {
            $table.find('.linkcentral-loading-overlay').show();
        }
    }

    setupEventListeners() {
        // Set up event listeners for pagination controls (timeframe selector removed)
        jQuery('#linkcentral-top-links-table').next('.tablenav').on('click', '.first-page', (e) => this.handlePagination(e, 1));
        jQuery('#linkcentral-top-links-table').next('.tablenav').on('click', '.prev-page', (e) => this.handlePagination(e, this.currentPage - 1));
        jQuery('#linkcentral-top-links-table').next('.tablenav').on('click', '.next-page', (e) => this.handlePagination(e, this.currentPage + 1));
        jQuery('#linkcentral-top-links-table').next('.tablenav').on('click', '.last-page', (e) => this.handlePagination(e, this.totalPages));
        jQuery('#top-links-current-page').on('keydown', (e) => this.handlePageInput(e));
    }

    handleDateRangeChange(dateRange) {
        // Reset to first page when date range changes
        this.currentPage = 1;
        // Load top links based on the new date range
        this.loadTopLinks(dateRange);
    }

    handleSelectionChange(selection) {
        // Clear previous selections
        this.selectedLinkId = null;
        this.selectedCategoryId = null;
        
        // Set the new selection
        if (selection.linkId) {
            this.selectedLinkId = selection.linkId;
        } else if (selection.categoryId) {
            this.selectedCategoryId = selection.categoryId;
        }
        
        this.currentPage = 1;
        const currentRange = this.dateRangeSelector.getCurrentDateRange();
        this.loadTopLinks(currentRange);
    }

    handlePagination(e, page) {
        e.preventDefault();
        // Validate the page number and load top links for the specified page
        if (page >= 1 && page <= this.totalPages && page !== this.currentPage) {
            const currentRange = this.dateRangeSelector.getCurrentDateRange();
            this.loadTopLinks(currentRange, page, true); // true = manual navigation
        }
    }

    handlePageInput(e) {
        if (e.keyCode === 13) { // Enter key
            e.preventDefault();
            const page = parseInt(e.target.value);
            // Validate the page number and load top links for the specified page
            if (page > 0 && page <= this.totalPages) {
                const currentRange = this.dateRangeSelector.getCurrentDateRange();
                this.loadTopLinks(currentRange, page, true); // true = manual navigation
            }
        }
    }

    loadTopLinks(dateRange, page = 1, isManualNavigation = false) {
        // Show loading spinner as an overlay instead of replacing content
        const $table = jQuery('#linkcentral-top-links-table');
        $table.find('.linkcentral-loading-overlay').show();
        
        // Prepare data for AJAX request
        const ajaxData = {
            action: 'linkcentral_get_top_links',
            nonce: linkcentral_admin.nonce,
            page: page
        };

        // Add selected link ID if available
        if (this.selectedLinkId) {
            ajaxData.link_id = this.selectedLinkId;
        }

        // Add selected category ID if available
        if (this.selectedCategoryId) {
            ajaxData.category_id = this.selectedCategoryId;
        }
        
        // Add manual navigation flag if this is manual navigation
        if (isManualNavigation) {
            ajaxData.is_manual_navigation = true;
        }

        // Add date range parameters based on the current selection
        if (dateRange) {
            if (dateRange.preset === 'since_start') {
                ajaxData.since_start = true;
            } else if (dateRange.formattedStartDate && dateRange.formattedEndDate) {
                ajaxData.start_date = dateRange.formattedStartDate;
                ajaxData.end_date = dateRange.formattedEndDate;
            } else {
                // Fallback to preset-based timeframe
                ajaxData.timeframe = dateRange.preset || '7';
            }
        } else {
            // Default fallback
            ajaxData.timeframe = '7';
        }
        
        // Make an AJAX request to fetch top links data
        jQuery.ajax({
            url: linkcentral_admin.ajax_url,
            type: 'POST',
            data: ajaxData,
            success: (response) => {
                // Hide the loading overlay
                $table.find('.linkcentral-loading-overlay').hide();
                
                if (response.success) {
                    // Update the table with the fetched data
                    this.updateTopLinksTable(response.data);
                } else {
                    console.error('Error loading top links:', response.data);
                }
            },
            error: (jqXHR, textStatus, errorThrown) => {
                // Hide the loading overlay on error too
                $table.find('.linkcentral-loading-overlay').hide();
                console.error('AJAX error:', textStatus, errorThrown);
            }
        });
    }

    updateTopLinksTable(data) {
        // Set itemsPerPage from the response if not already set
        if (this.itemsPerPage === null && data.items_per_page) {
            this.itemsPerPage = data.items_per_page;
        }
        
        const $table = jQuery('#linkcentral-top-links-table tbody');
        const $tableElement = jQuery('#linkcentral-top-links-table');
        $table.empty();

        if (!data.links || data.links.length === 0) {
            const colspan = this.trackUniqueVisitors ? 6 : 5;
            $table.append(`
                <tr>
                    <td colspan="${colspan}">${this.__('No data available for the selected period.', 'linkcentral')}</td>
                </tr>
            `);
            $tableElement.removeClass('linkcentral-has-highlighted-links');
            return;
        }

        // Remove striped class when highlighting is active
        const hasHighlightedLinks = data.selected_link_id != null || data.selected_category_id != null;
        $tableElement.toggleClass('striped', !hasHighlightedLinks);

        data.links.forEach(link => {
            // Check if this link is selected (individual link selection)
            const isSelected = data.selected_link_id != null && parseInt(link.ID) === parseInt(data.selected_link_id);
            
            // Check if this link belongs to the selected category
            const isInSelectedCategory = data.selected_category_id != null && link.is_in_selected_category;
            
            let rowClass = link.is_deleted ? 'linkcentral-deleted-link' : (link.is_trashed ? 'linkcentral-trashed-link' : (link.is_private ? 'linkcentral-private-link' : ''));
            
            // Add selected class if this is the selected link (individual selection takes precedence)
            if (isSelected) {
                rowClass += ' linkcentral-selected-link';
            }
            // Add category highlight class if this link belongs to the selected category and no individual link is selected
            else if (isInSelectedCategory) {
                rowClass += ' linkcentral-category-highlight';
            }
            
            const deletedIndicator = link.is_deleted ? ' <span class="dashicons dashicons-no" title="This link has been deleted"></span>' : '';
            const trashedIndicator = link.is_trashed ? ' <span class="dashicons dashicons-trash" title="This link is in the trash"></span>' : '';
            const privateIndicator = link.is_private ? ' <span class="dashicons dashicons-lock" title="This link is private"></span>' : '';
            const dynamicIndicator = link.has_dynamic_rules ? ' <span class="dashicons dashicons-randomize" title="Dynamic redirects enabled"></span>' : '';

            let uniqueClicksColumn = '';
            if (this.trackUniqueVisitors) {
                uniqueClicksColumn = `<td class="linkcentral-column-unique-clicks">${link.unique_clicks}</td>`;
            }

            const row = `
                <tr class="${rowClass}">
                    <td class="linkcentral-column-rank">${link.rank}</td>
                    <td class="linkcentral-column-title">
                        ${link.is_deleted ? 'Deleted Link' : `<a href="${link.edit_link}">${link.post_title}</a>`}
                        ${deletedIndicator}${trashedIndicator}${privateIndicator}
                    </td>
                    <td class="linkcentral-column-slug">${link.is_deleted ? '' : '/' + link.slug}</td>
                    <td class="linkcentral-column-destination_url">${link.is_deleted ? '' : link.destination_url_truncated}${dynamicIndicator}</td>
                    <td class="linkcentral-column-total-clicks">${link.total_clicks}</td>
                    ${uniqueClicksColumn}
                </tr>
            `;
            $table.append(row);
        });

        this.updatePagination(data);
    }

    updatePagination(data) {
        // Update pagination variables
        this.currentPage = data.current_page;
        this.totalPages = data.total_pages;
        this.totalItems = data.total_items;

        const $pagination = jQuery('#linkcentral-top-links-table').next('.tablenav').find('.tablenav-pages');
        const startItem = (this.currentPage - 1) * this.itemsPerPage + 1;
        const endItem = Math.min(this.currentPage * this.itemsPerPage, this.totalItems);
        
        // Update pagination display
        $pagination.find('.displaying-num').text(this.totalItems > 0 ? `${this.totalItems} items` : 'No items');
        $pagination.find('.total-pages').text(this.totalPages);
        $pagination.find('#top-links-current-page').val(this.currentPage);
        $pagination.find('.tablenav-paging-text').text(` of ${this.totalPages}`);

        // Enable/disable pagination buttons based on current page
        $pagination.find('.first-page, .prev-page').toggleClass('disabled', this.currentPage === 1);
        $pagination.find('.last-page, .next-page').toggleClass('disabled', this.currentPage === this.totalPages);

        // Update the paging text
        if (this.totalItems > 0) {
            $pagination.find('.tablenav-paging-text').text(`${startItem}-${endItem} of ${this.totalItems}`);
        } else {
            $pagination.find('.tablenav-paging-text').text('0 items');
        }
    }
}

export default MostPopularLinks;