import {Line} from 'react-chartjs-2';
import {
	Chart as ChartJS,
	CategoryScale,
	LinearScale,
	PointElement,
	LineElement,
	Title,
	Tooltip,
	Legend
} from 'chart.js';
import {__} from '@wordpress/i18n';
import {dateI18n} from '@wordpress/date';

ChartJS.register(
	CategoryScale,
	LinearScale,
	PointElement,
	LineElement,
	Title,
	Tooltip,
	Legend
);

const rgba = ( hex, a = 1 ) =>
	`rgba(${parseInt( hex.slice( 1 ), 16 ) >> 16 & 255},
        ${parseInt( hex.slice( 1 ), 16 ) >> 8 & 255},
        ${parseInt( hex.slice( 1 ), 16 ) & 255},
        ${a})`;

const METRIC_STYLES = {
	impressions:    {
		label:           __( 'Impressions', 'adpresso' ),
		borderColor:     rgba( '#3B82B6' ),
		backgroundColor: rgba( '#3B82B6', 0.5 ),
		yAxisID:         'yLeft' // Standard: linke Achse
	},
	clicks:         {
		label:           __( 'Clicks', 'adpresso' ),
		borderColor:     rgba( '#A78C2D' ),
		backgroundColor: rgba( '#A78C2D', 0.5 ),
		yAxisID:         'yLeft'
	},
	ctr:            {
		label:           __( 'CTR (%)', 'adpresso' ),
		borderColor:     rgba( '#34875C' ),
		backgroundColor: rgba( '#34875C', 0.5 ),
		yAxisID:         'yRight' // Rate-Metriken auf die rechte Achse
	},
	viewability:    {
		label:           __( 'Active View Rate (%)', 'adpresso' ),
		borderColor:     rgba( '#62499C' ),
		backgroundColor: rgba( '#62499C', 0.5 ),
		yAxisID:         'yRight',
		premium:         true
	},
	impressions_av: {
		label:           __( 'Active View Impressions', 'adpresso' ),
		borderColor:     rgba( '#9E3B32' ),
		backgroundColor: rgba( '#9E3B32', 0.5 ),
		yAxisID:         'yLeft',
		premium:         true
	}
};

const {dateFormat} = window.adpressoAnalyticsData || {dateFormat: 'F j, Y'};

const ChartRenderer = ( {chartData, visibleMetrics, compareData = null} ) => {
	const datasets = [];
	const labels = chartData.map( item => {
		if ( !item.date ) {
			return '-';
		}

		try {
			return dateI18n( dateFormat, `${item.date}T12:00:00` );
		} catch ( e ) {
			return item.date;
		}
	} );

	visibleMetrics.forEach( key => {
		if ( !METRIC_STYLES[key] ) {
			return;
		}

		datasets.push( {
			...METRIC_STYLES[key],
			data: chartData.map( item => item[key] )
		} );

		if ( compareData ) {
			datasets.push( {
				...METRIC_STYLES[key],
				label:           `${METRIC_STYLES[key].label} (Previous)`,
				data:            compareData.map( item => item[key] ),
				borderColor:     METRIC_STYLES[key].backgroundColor,
				backgroundColor: 'transparent',
				borderDash:      [5, 5],
				pointRadius:     2
			} );
		}
	} );

	const scales = {
		x:      {},
		yLeft:  {
			type:     'linear',
			display:  true,
			position: 'left',
			title:    {display: true, text: 'Count'}
		},
		yRight: {
			type:     'linear',
			display:  false,
			position: 'right',
			title:    {display: true, text: 'Rate (%)'},
			grid:     {drawOnChartArea: false}
		}
	};

	const isImpressionsAndClicks =
		visibleMetrics.length === 2 &&
		visibleMetrics.includes( 'impressions' ) &&
		visibleMetrics.includes( 'clicks' );

	if ( isImpressionsAndClicks ) {
		datasets.find( d => d.label === 'Clicks' ).yAxisID = 'yRight';
		if ( compareData ) {
			datasets.find( d => d.label === 'Clicks (Previous)' ).yAxisID = 'yRight';
		}
		scales.yRight.display = true;
		scales.yRight.title.text = 'Clicks';
	} else {
		const hasRateMetric = visibleMetrics.some( key => METRIC_STYLES[key]?.yAxisID === 'yRight' );
		if ( hasRateMetric ) {
			scales.yRight.display = true;
		}
	}

	const hasCountMetric = visibleMetrics.some( key => METRIC_STYLES[key]?.yAxisID === 'yLeft' );
	if ( !hasCountMetric && scales.yRight.display ) {
		scales.yLeft.display = false;
		datasets.forEach( d => d.yAxisID = 'yRight' );
		scales.yRight.position = 'left';
	}

	const data = {
		labels:   labels,
		datasets: datasets
	};

	const options = {
		responsive:  true,
		interaction: {mode: 'index', intersect: false},
		plugins:     {
			legend: false,
			title:  {display: false, text: 'Performance Overview'}
		},
		scales:      scales
	};

	return <Line options={options} data={data}/>;
};

export default ChartRenderer;
