import ApexCharts from 'apexcharts';

// Import WordPress i18n function
const { __ } = wp.i18n;

class TotalClicks {
    constructor(dateRangeSelector, linkSelector) {
        this.chart = null;
        this.trackUniqueVisitors = linkcentral_insights_data.track_unique_visitors === '1';
        this.dateRangeSelector = dateRangeSelector;
        this.linkSelector = linkSelector;
        this.isPremium = linkcentral_insights_data.can_use_premium_code__premium_only === '1';
    }

    init() {
        this.setupLoadingOverlay();
        this.initChart();
        
        // Listen for date range changes from the shared selector
        this.dateRangeSelector.addEventListener((dateRange) => {
            this.handleDateRangeChange(dateRange);
        });
        
        // Listen for link selection changes from the shared selector
        this.linkSelector.addEventListener((linkSelection) => {
            this.handleLinkSelectionChange(linkSelection);
        });
    }

    handleDateRangeChange(dateRange) {
        this.loadDataWithCurrentSelection(dateRange);
    }

    handleLinkSelectionChange(linkSelection) {
        const currentRange = this.dateRangeSelector.getCurrentDateRange();
        if (currentRange) {
            this.loadDataWithCurrentSelection(currentRange);
        }
    }

    loadDataWithCurrentSelection(dateRange) {
        const linkSelection = this.linkSelector.getCurrentSelection();
        if (linkSelection.linkId) {
            this.loadSpecificLinkStats(linkSelection.linkId, dateRange.preset, dateRange.formattedStartDate, dateRange.formattedEndDate);
        } else if (linkSelection.categoryId) {
            this.loadSpecificCategoryStats(linkSelection.categoryId, dateRange.preset, dateRange.formattedStartDate, dateRange.formattedEndDate);
        } else {
            this.loadStats(dateRange.preset, dateRange.formattedStartDate, dateRange.formattedEndDate);
        }
    }

    // CHART CONFIGURATION
    // -------------------

    initChart() {
        const options = this.getChartOptions();
        this.chart = new ApexCharts(document.querySelector("#linkcentral-total-clicks-chart"), options);
        this.chart.render();
    }

    getChartOptions() {
        const options = {
            chart: { 
                type: 'area',
                height: 300,
                toolbar: { show: true },
                zoom: { type: 'x', enabled: false },
            },
            series: [{ name: __('Total Clicks', 'linkcentral'), data: [] }],
            grid: {
                row: {
                    colors: ['#F6F7F7', 'transparent'],
                  opacity: 0.5
                },
            },
            xaxis: {
                type: 'datetime',
                tooltip: { enabled: false },
                labels: { 
                    datetimeUTC: true,
                    format: 'dd MMM yyyy'
                }
            },
            yaxis: {
                title: { text: __('Clicks', 'linkcentral') },
                min: 0
            },
            stroke: {
                curve: 'smooth',
                width: 3
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.5,
                    opacityTo: 0,
                    stops: [0, 90, 100]
                }
            },
            colors: ['#12668A'],
            tooltip: { 
                x: { 
                    format: 'dd MMM yyyy',
                    show: true
                } 
            },
            legend: {
              position: 'top',
              horizontalAlign: 'right',
              floating: true,
              offsetY: 0,
            }
        };

        if (this.trackUniqueVisitors) {
            options.series.push({ name: __('Unique Clicks', 'linkcentral'), data: [] });
            options.colors.push('rgb(255, 205, 86)');
        }

        return options;
    }

    updateChart(data) {
        if (!data || !data.labels || !data.clicks) return;

        // Update shared date range selector for 'since_start' mode
        if (data.labels.length > 0 && this.dateRangeSelector) {
            const firstDate = new Date(data.labels[0]);
            const lastDate = new Date(data.labels[data.labels.length - 1]);
            
            const currentRange = this.dateRangeSelector.getCurrentDateRange();
            const isDateRangeChanged = 
                !currentRange || 
                !currentRange.startDate || 
                !currentRange.endDate || 
                currentRange.startDate.getTime() !== firstDate.getTime() || 
                currentRange.endDate.getTime() !== lastDate.getTime();
            
            if (isDateRangeChanged && this.dateRangeSelector.getCurrentPreset() === 'since_start') {
                this.dateRangeSelector.updateDateRange(firstDate, lastDate, 'since_start');
            }
        }

        // Prepare series data
        const seriesData = [
            {
                name: __('Total Clicks', 'linkcentral'),
                data: data.labels.map((label, index) => [
                    new Date(label).getTime(), 
                    data.clicks[index]
                ])
            }
        ];

        if (this.trackUniqueVisitors && data.unique_clicks) {
            seriesData.push({
                name: __('Unique Clicks', 'linkcentral'),
                data: data.labels.map((label, index) => [
                    new Date(label).getTime(), 
                    data.unique_clicks[index]
                ])
            });
        }

        // Update chart
        this.chart.updateOptions({
            series: seriesData,
            xaxis: {
                type: 'datetime',
                categories: data.labels
            },
            dataLabels: {
                enabled: data.labels.length <= 30,
                formatter: function(val) { return val; },
                style: {
                    fontSize: '11px',
                    fontWeight: 'bold'
                }
            },
            ...(data.labels.length > 30 && { stroke: { width: 2 } }),
        });
    }

    // DATA LOADING
    // -----------

    loadStats(days, startDate = null, endDate = null) {
        this.showLoading();
        
        const requestData = {
            action: 'linkcentral_get_stats',
            nonce: linkcentral_admin.nonce,
            days: days,
            start_date: startDate,
            end_date: endDate,
            
        };
        
        jQuery.ajax({
            url: linkcentral_admin.ajax_url,
            type: 'POST',
            data: requestData,
            success: (response) => {
                if (response.success) {
                    this.updateChart(response.data);
                }
            },
            complete: () => {
                this.hideLoading();
            }
        });
    }

    loadSpecificLinkStats(linkId, days, startDate = null, endDate = null) {
        this.showLoading();
        jQuery.ajax({
            url: linkcentral_admin.ajax_url,
            type: 'POST',
            data: {
                action: 'linkcentral_get_link_stats',
                nonce: linkcentral_admin.nonce,
                link_id: linkId,
                days: days,
                start_date: startDate,
                end_date: endDate,
                
            },
            success: (response) => {
                if (response.success) {
                    this.updateChart(response.data);
                }
            },
            complete: () => {
                this.hideLoading();
            }
        });
    }

    loadSpecificCategoryStats(categoryId, days, startDate = null, endDate = null) {
        this.showLoading();
        jQuery.ajax({
            url: linkcentral_admin.ajax_url,
            type: 'POST',
            data: {
                action: 'linkcentral_get_category_stats',
                nonce: linkcentral_admin.nonce,
                category_id: categoryId,
                days: days,
                start_date: startDate,
                end_date: endDate,
                
            },
            success: (response) => {
                if (response.success) {
                    this.updateChart(response.data);
                }
            },
            complete: () => {
                this.hideLoading();
            }
        });
    }

    // EVENT HANDLING & UI
    // ------------------

    // LOADING OVERLAY
    // --------------

    setupLoadingOverlay() {
        const $container = jQuery("#linkcentral-total-clicks-chart").parent();
        $container.css('position', 'relative');
        
        if ($container.find('.linkcentral-loading-overlay').length === 0) {
            $container.append(`
                <div class="linkcentral-loading-overlay" style="display: none;">
                    <span class="spinner is-active"></span>
                </div>
            `);
        }
    }

    showLoading() {
        jQuery("#linkcentral-total-clicks-chart").parent().find('.linkcentral-loading-overlay').show();
    }

    hideLoading() {
        jQuery("#linkcentral-total-clicks-chart").parent().find('.linkcentral-loading-overlay').hide();
    }
}

export default TotalClicks;