import { renderInsightLinkTitle } from '../ui/link-title-cell';
import { isPremiumUser } from '../utils/premium';
import { escapeHtml, escapeAttr } from '../utils/html';

class RecentClicks {
    constructor(store) {
        this.__ = wp.i18n.__;
        this.store = store;
        this.currentPage = 1;
        this.totalPages = 1;
        this.trackUserAgent = linkcentral_admin.track_user_agent;
        this.geolocationService = linkcentral_admin.geolocation_service;
        // Match insights-page.php: country column is premium + geolocation enabled.
        this.showCountryColumn = isPremiumUser()
            && this.geolocationService
            && this.geolocationService !== 'none'
            && this.geolocationService !== '';
    }

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

        this.store.subscribe((snapshot, loading) => {
            const $table = jQuery('#linkcentral-recent-clicks-table');
            if (loading && !snapshot?.widgets?.recent_clicks) {
                $table.find('.linkcentral-loading-overlay').show();
            } else {
                $table.find('.linkcentral-loading-overlay').hide();
            }
            if (snapshot?.widgets?.recent_clicks) {
                this.updateRecentClicksTable(snapshot.widgets.recent_clicks);
            }
        });
    }

    addLoadingOverlay() {
        const $table = jQuery('#linkcentral-recent-clicks-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 $pagination = jQuery('#linkcentral-recent-clicks-table').next('.tablenav');
        $pagination.on('click', '.first-page', (e) => this.handlePagination(e, 1));
        $pagination.on('click', '.prev-page', (e) => this.handlePagination(e, this.currentPage - 1));
        $pagination.on('click', '.next-page', (e) => this.handlePagination(e, this.currentPage + 1));
        $pagination.on('click', '.last-page', (e) => this.handlePagination(e, this.totalPages));
        jQuery('#recent-clicks-current-page').on('keydown', (e) => this.handlePageInput(e));
    }

    handlePagination(e, page) {
        e.preventDefault();
        this.store.loadWidgets(['recent_clicks'], {
            recent_clicks: { 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(['recent_clicks'], {
                    recent_clicks: { page },
                });
            }
        }
    }

    renderDrilldownSpan(baseClass, title, textContent, groupKey, value) {
        const attrs = value && value !== '-'
            ? ` class="${baseClass} linkcentral-drilldown-trigger" data-drilldown-group="${escapeAttr(groupKey)}" data-drilldown-value="${escapeAttr(value)}"`
            : ` class="${baseClass}"`;

        if (textContent !== undefined) {
            return `<span${attrs} title="${escapeAttr(title)}">${escapeHtml(textContent)}</span>`;
        }

        return `<span${attrs} title="${escapeAttr(title)}"></span>`;
    }

    renderUserAgentCell(info) {
        if (!info.browser || !info.device || info.browser === '-' || info.device === '-') {
            return '<td class="linkcentral-column-user-agent">-</td>';
        }

        const browserSpan = this.renderDrilldownSpan(
            `linkcentral-browser-icon linkcentral-browser-${info.browser.toLowerCase()}`,
            info.browser,
            undefined,
            'browser',
            info.browser
        );
        const deviceSpan = this.renderDrilldownSpan(
            `dashicons ${info.device_icon}`,
            info.device,
            undefined,
            'device',
            info.device
        );
        const osSpan = this.renderDrilldownSpan(
            'linkcentral-os-info',
            info.os,
            info.os,
            'operating_system',
            info.os
        );

        return `
            <td class="linkcentral-column-user-agent">
                ${browserSpan}
                ${deviceSpan}
                ${osSpan}
            </td>
        `;
    }

    renderCountryCell(click) {
        if (!this.showCountryColumn) {
            return '';
        }

        const country = (click.country || 'XX').toUpperCase();
        const label = click.country_label
            || (country === 'XX' ? this.__('Unknown', 'linkcentral') : country);

        return `<td class="linkcentral-column-country">
            <span
                class="flag flag-${country.toLowerCase()} linkcentral-drilldown-trigger"
                data-drilldown-group="geo"
                data-geo-type="country"
                data-geo-country="${escapeAttr(country)}"
                data-geo-label="${escapeAttr(label)}"
                title="${escapeAttr(label)}"
            ></span>
        </td>`;
    }

    renderReferringUrlCell(click, referringUrl) {
        const drilldown = click.referrer_drilldown;
        if (!drilldown?.group || !drilldown?.value) {
            return `<td class="linkcentral-column-referring_url">${escapeHtml(referringUrl)}</td>`;
        }

        let display = referringUrl;
        if (!display) {
            if (drilldown.value === 'Direct') {
                display = this.__('Direct', 'linkcentral');
            } else if (drilldown.value === 'Internal') {
                display = this.__('Internal', 'linkcentral');
            } else {
                display = drilldown.value;
            }
        }

        return `<td class="linkcentral-column-referring_url">
            <button
                type="button"
                class="linkcentral-drilldown-trigger linkcentral-drilldown-link"
                data-drilldown-group="${escapeAttr(drilldown.group)}"
                data-drilldown-value="${escapeAttr(drilldown.value)}"
            >${escapeHtml(display)}</button>
        </td>`;
    }

    getTableColspan() {
        let colspan = 5;
        if (this.trackUserAgent) {
            colspan += 1;
        }
        if (this.showCountryColumn) {
            colspan += 1;
        }
        return colspan;
    }

    updateRecentClicksTable(data) {
        const $table = jQuery('#linkcentral-recent-clicks-table tbody');
        $table.empty();

        if (!data.clicks || data.clicks.length === 0) {
            $table.append(`
                <tr>
                    <td colspan="${this.getTableColspan()}">${this.__('No data available for the selected period.', 'linkcentral')}</td>
                </tr>
            `);
            this.updatePagination(data);
            return;
        }

        data.clicks.forEach((click) => {
            const userAgentCell = this.trackUserAgent ? this.renderUserAgentCell(click.user_agent_info) : '';

            const deletedIndicator = click.is_deleted ? ' <span class="dashicons dashicons-no" title="This link has been deleted"></span>' : '';
            const trashedIndicator = click.is_trashed ? ' <span class="dashicons dashicons-trash" title="This link is in the trash"></span>' : '';
            const privateIndicator = click.is_private ? ' <span class="dashicons dashicons-lock" title="This link is private"></span>' : '';
            const rowClass = click.is_deleted ? 'linkcentral-deleted-link' : (click.is_trashed ? 'linkcentral-trashed-link' : (click.is_private ? 'linkcentral-private-link' : ''));

            const titleCell = renderInsightLinkTitle({
                linkId: click.link_id,
                title: click.post_title,
                editLink: click.edit_link,
                isDeleted: click.is_deleted,
            });
            const slug = click.is_deleted ? '' : '/' + click.slug;
            const referringUrl = click.is_deleted ? '' : click.referring_url;
            const destinationUrl = click.destination_url_truncated;
            const countryCell = this.renderCountryCell(click);
            const referringUrlCell = this.renderReferringUrlCell(click, referringUrl);

            $table.append(`
                <tr class="${rowClass}">
                    <td class="linkcentral-column-title">${titleCell}${deletedIndicator}${trashedIndicator}${privateIndicator}</td>
                    <td class="linkcentral-column-slug">${slug}</td>
                    ${referringUrlCell}
                    <td class="linkcentral-column-destination_url">${destinationUrl}</td>
                    ${userAgentCell}
                    ${countryCell}
                    <td class="linkcentral-column-timestamp">${click.formatted_date}</td>
                </tr>
            `);
        });

        this.updatePagination(data);
    }

    updatePagination(data) {
        const $pagination = jQuery('#linkcentral-recent-clicks-table').next('.tablenav').find('.tablenav-pages');

        $pagination.find('.total-pages').text(data.total_pages);
        $pagination.find('#recent-clicks-current-page').val(data.current_page);

        const startItem = (data.current_page - 1) * data.items_per_page + 1;
        const endItem = Math.min(data.current_page * data.items_per_page, data.total_items);
        $pagination.find('.displaying-num').text(`${startItem}-${endItem} of ${data.total_items} items`);

        $pagination.find('.first-page, .prev-page').toggleClass('disabled', data.current_page <= 1);
        $pagination.find('.next-page, .last-page').toggleClass('disabled', data.current_page >= data.total_pages);

        this.currentPage = data.current_page;
        this.totalPages = data.total_pages;
    }
}

export default RecentClicks;
