import React, { useRef } from "react";
import {
    Chart,
    LinearScale,
    PointElement,
    LineElement,
    ChartOptions,
} from "chart.js";
import { Line } from "react-chartjs-2";

import CursorsPlugin from "chartjs-plugin-cursors";
import { CursorOptions } from "chartjs-plugin-cursors/dist/types";

Chart.register(LinearScale, PointElement, LineElement, CursorsPlugin);

const options: ChartOptions<"line"> & {
    plugins: { cursors?: CursorOptions };
} = {
    responsive: true,
    events: ["mousedown", "mouseup", "mousemove"],
    scales: {
        x: {
            type: "linear",
        },
        y: {
            type: "linear",
        },
    },
    plugins: {
        cursors: {
            enabled: true,
            visible: true,
            positions: [{ x: 20, y: 400 }],
            callbacks: {
                afterMove: (positions) => {
                    console.log("positions 2", positions);
                },
            },
        },
    },
};

const data = {
    datasets: [
        {
            label: "Dataset 1",
            data: Array.from({ length: 100 }, (_, index) => ({
                x: index,
                y: Math.random() * 1000,
            })),
            borderColor: "rgb(255, 99, 132)",
            backgroundColor: "rgba(255, 99, 132, 0.5)",
        },
    ],
};

function App() {
    const chartRef = useRef<Chart<"line">>(null);

    const centreCursors = () => {
        console.log(
            chartRef.current?.options.plugins?.cursors?.callbacks?.afterMove
        );
        if (!chartRef.current) return;
        if (!chartRef.current.options.plugins?.cursors?.callbacks) return;
        chartRef.current.options.plugins.cursors.callbacks.afterMove = (
            positions
        ) => {
            console.log("positions new", positions);
        };
        chartRef.current?.cursors.centreCursors(chartRef.current as any);
    };

    return (
        <div style={{ width: "800px", margin: "0 auto" }}>
            <h1>Example page for chartjs-plugin-cursors</h1>
            <button onClick={centreCursors}>Centre cursors</button>
            <Line options={options} data={data} ref={chartRef} />
        </div>
    );
}

export default App;
