import {formatDate} from "../../includes/functions";

const {useEffect, useRef} = React;

export default function ActivationChart({data}) {

    const {activations = []} = data;

    const containerRef = useRef(null);

    const dates = activations.map(item => formatDate(item.date));
    const values = activations.map(item => item.count);

    useEffect(() => {

        const ctx = containerRef.current.querySelector('#darkModeActivationChart').getContext('2d');

        const darkModeActivationChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: dates,
                datasets: [{
                    label: 'Dark Mode Activations',
                    data: values,
                    borderColor: 'rgba(103, 94, 213, .7)', // Color of the line
                    borderWidth: 2,
                    fill: false
                }]
            },
            options: {
                maintainAspectRatio: false,
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Activations'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: 'Date'
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: true
                    },
                    tooltip: {
                        enabled: true,
                        callbacks: {
                            label: function (context) {
                                return `Activations: ${context.parsed.y}`;
                            }
                        }
                    }
                }
            }
        });

        return () => {
            darkModeActivationChart.destroy();
        }
    }, [activations]);

    return (
        <div className="analytics-box activation-chart" ref={containerRef}>
            <span className="analytics-box-title">
                {wp.i18n.__('Daily Dark Mode Activation Chart', 'dracula-dark-mode')}
            </span>

            <div className="analytics-box-content">
                <canvas id="darkModeActivationChart" height="400"></canvas>
            </div>

        </div>
    )
}