<script lang="ts">
	import {
		Chart,
		CategoryScale,
		LinearScale,
		PointElement,
		LineElement,
		Title,
		Tooltip,
		Legend,
		LineController
	} from 'chart.js';
	import { onMount } from 'svelte';

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

	interface IProps {
		color?: string;
		data?: any[];
		title?: string;
		legend?: string;
	}

	const { color = 'green', data = [], title = '', legend = '' }: IProps = $props();

	function updateGraph() {
		const ctx = document.getElementById(id) as HTMLCanvasElement;
		const chart = new Chart(ctx, {
			type: 'line',
			data: {
				labels: data.map((d) => d.label),
				datasets: [
					{
						label: legend,
						data: data.map((d) => d.value),
						borderColor: color,
						backgroundColor: color,
						fill: false,
						tension: 0.1
					}
				]
			},
			options: {
				responsive: true,
				plugins: {
					title: {
						display: true,
						text: title
					},
					legend: {
						display: true
					}
				}
			}
		});
	}

	const id = 'graph-' + crypto.randomUUID();

	onMount(() => {
		updateGraph();
	});
</script>

<div>
	<canvas {id}></canvas>
</div>
