import React from "react";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  TimeScale,
} from "chart.js";
import { Line } from "react-chartjs-2";
import "chartjs-adapter-date-fns";

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

ChartJS.defaults.color = "#D9D9D9";

export interface LineChartProps {
  title: string;
  data: {
    labels: string[];
    values: number[];
  };
}

/**
 * This component is a temporary
 * We should be using @nocodelytics/components instead but it's not ready yet
 * This works for the first version
 */
export const LineChart: React.FC<LineChartProps> = (props) => {
  return (
    <div
      style={{
        position: "relative",
        height: "100%",
        backgroundColor: "#404040",
        padding: "10px",
        border: "1px solid #212121",
      }}
    >
      <Line
        style={{ height: "100%", width: "100%" }}
        options={{
          responsive: true,
          maintainAspectRatio: false,
          interaction: { mode: "nearest", intersect: false },
          scales: {
            y: { ticks: { stepSize: 1 } },
            x: {
              type: "time",
            },
          },
          plugins: {
            title: {
              display: Boolean(props.title),
              text: props.title,
            },
            tooltip: {
              animation: false,
              backgroundColor: "#2b2b2b",
              bodyColor: "white",
              displayColors: false,
              mode: "nearest",
              caretSize: 0,
              borderWidth: 1,
              borderColor: "#212121",
              cornerRadius: 0,
              xAlign: "center",
              yAlign: "center",
              callbacks: {
                title: () => "",
                label: (item) => {
                  const date = new Date(item.parsed.x).toLocaleDateString();
                  return `${date}: ${item.parsed.y}`;
                },
              },
            },
          },
        }}
        data={{
          labels: props.data.labels,
          datasets: [
            {
              pointStyle: "line",
              data: props.data.values,
              borderColor: "#0073E6",
              backgroundColor: "#0073E6",
            },
          ],
        }}
      />
    </div>
  );
};
