import { renderInsightLinkTitle } from '../ui/link-title-cell';

function isLinkScopeActive(store) {
    const { link_id: linkId, category_id: categoryId } = store.filters;
    return !!(linkId || categoryId);
}

class MostPopularLinks {
    constructor(store) {
        this.__ = wp.i18n.__;
        this.store = store;
        this.currentPage = 1;
        this.totalPages = 1;
        this.totalItems = 0;
        this.itemsPerPage = null;
        this.trackUniqueVisitors = linkcentral_insights_data.track_unique_visitors === '1';
    }

    init() {
        this.addLoadingOverlay();
        this.setupEventListeners();
        this.updateSectionVisibility();

        this.store.subscribe((snapshot, loading) => {
            this.updateSectionVisibility();

            const $table = jQuery('#linkcentral-top-links-table');
            if (loading) {
                $table.find('.linkcentral-loading-overlay').show();
            } else {
                $table.find('.linkcentral-loading-overlay').hide();
            }
            if (snapshot?.widgets?.top_links) {
                this.updateTopLinksTable(snapshot.widgets.top_links);
            }
        });
    }

    updateSectionVisibility() {
        jQuery('#linkcentral-top-links-container').toggle(!isLinkScopeActive(this.store));
    }

    addLoadingOverlay() {
        const $table = jQuery('#linkcentral-top-links-table');
        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>
            `);
        }
    }

    setupEventListeners() {
        const $nav = jQuery('#linkcentral-top-links-table').next('.tablenav');
        $nav.on('click', '.first-page', (e) => this.handlePagination(e, 1));
        $nav.on('click', '.prev-page', (e) => this.handlePagination(e, this.currentPage - 1));
        $nav.on('click', '.next-page', (e) => this.handlePagination(e, this.currentPage + 1));
        $nav.on('click', '.last-page', (e) => this.handlePagination(e, this.totalPages));
        jQuery('#top-links-current-page').on('keydown', (e) => this.handlePageInput(e));
    }

    handlePagination(e, page) {
        e.preventDefault();
        if (page >= 1 && page <= this.totalPages && page !== this.currentPage) {
            this.store.loadWidgets(['top_links'], {
                top_links: { page },
            });
        }
    }

    handlePageInput(e) {
        if (e.keyCode === 13) {
            e.preventDefault();
            const page = parseInt(e.target.value, 10);
            if (page > 0 && page <= this.totalPages) {
                this.store.loadWidgets(['top_links'], {
                    top_links: { page },
                });
            }
        }
    }

    updateTopLinksTable(data) {
        if (this.itemsPerPage === null && data.items_per_page) {
            this.itemsPerPage = data.items_per_page;
        }

        const $table = jQuery('#linkcentral-top-links-table tbody');
        $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>
            `);
            this.updatePagination(data);
            return;
        }

        data.links.forEach((link) => {
            const rowClass = link.is_deleted ? 'linkcentral-deleted-link' : (link.is_trashed ? 'linkcentral-trashed-link' : (link.is_private ? 'linkcentral-private-link' : ''));

            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 titleCell = renderInsightLinkTitle({
                linkId: link.ID,
                title: link.post_title,
                editLink: link.edit_link,
                isDeleted: link.is_deleted,
            });

            $table.append(`
                <tr class="${rowClass}">
                    <td class="linkcentral-column-rank">${link.rank}</td>
                    <td class="linkcentral-column-title">
                        ${titleCell}${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>
            `);
        });

        this.updatePagination(data);
    }

    updatePagination(data) {
        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);

        $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('.first-page, .prev-page').toggleClass('disabled', this.currentPage === 1);
        $pagination.find('.last-page, .next-page').toggleClass('disabled', this.currentPage === this.totalPages);

        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;
