import ApexCharts from 'apexcharts';

const { __ } = wp.i18n;

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

    init() {
        this.setupLoadingOverlay();
        this.initChart();

        this.store.subscribe((snapshot, loading) => {
            if (loading) {
                this.showLoading();
            } else {
                this.hideLoading();
            }
            if (snapshot?.widgets?.clicks_over_time) {
                this.updateChart(snapshot.widgets.clicks_over_time);
            }
        });
    }

    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 || !this.chart) {
            return;
        }

        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],
                ]),
            });
        }

        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 } }),
        });
    }

    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;
