import React, { ReactNode, useState } from "react";
import { Trend, TrendPoint } from "../../plucky_client/plucky";
import { Bar } from "react-chartjs-2";
import styles from "./trend_cell.module.css";
import { DateTime } from "luxon";
import { QueryRange } from "utils";
import { Box, Tooltip } from "@chakra-ui/react";
import { ChartOptions, Chart, TooltipModel } from "chart.js";

export type TrendCellProps = {
  queryRange: QueryRange;
  trend: Trend;
};

export function TrendCell(props: TrendCellProps) {
  const [activePoint, setActivePoint] = useState<TrendPoint | null>(null);

  let trendPoints: TrendPoint[] =
    (props && props.trend && props.trend.points) || [];
  trendPoints = trendPoints.map((p: TrendPoint) => ({
    start: p.start,
    count: p.count || 0,
  }));

  const labels = [];
  for (let i = 0; i < trendPoints.length; i++) {
    labels.push("");
  }

  const counts = trendPoints.map((trendPoint) => trendPoint.count);
  const maxCount = Math.max(...counts);

  const data = {
    labels,
    datasets: [
      {
        data: trendPoints,
      },
    ],
  };
  let options: ChartOptions<"bar"> = {
    animation: {
      duration: 0, // general animation time
    },
    backgroundColor: "rgba(28,28,28,1)",
    datasets: {
      bar: {
        barPercentage: 0.7,
        borderWidth: 0,
        hoverBackgroundColor: "rgba(255, 214, 99, 0.9)",
        minBarLength: 1,
      },
    },
    interaction: {
      // Triggers interaction events (like hover) when the cursor
      // isn't directly over the bars.
      intersect: false,
    },
    // Necessary to size the chart with our height and widths.
    maintainAspectRatio: false,
    onClick: (e) => {
      console.log(activePoint);
    },
    parsing: {
      xAxisKey: "start",
      yAxisKey: "count",
    },
    plugins: {
      legend: {
        display: false,
      },
      tooltip: {
        // Triggers interaction events (like hover) when the cursor
        // isn't directly over the bars.
        intersect: false,
        enabled: false,
        // disable displaying the color box;
        displayColors: false,
        //
        external: (ctx: { chart: Chart; tooltip: TooltipModel<"bar"> }) => {
          const dataPoints = ctx?.tooltip?.dataPoints || [];
          if (dataPoints.length === 0 && activePoint) {
            setActivePoint(null);
            return;
          }

          const point = dataPoints[0].raw as TrendPoint;
          if (activePoint === null && point === null) {
            return;
          }
          if (activePoint === null || point === null) {
            setActivePoint(point);
            return;
          }
          if (
            activePoint.start === point.start &&
            activePoint.count === point.count
          ) {
            return;
          }
          setActivePoint(point);
        },
      },
    },
    scales: {
      y: {
        display: false,
        beginAtZero: true,
        max: maxCount,
      },
      x: {
        display: false,
      },
    },
  };

  let toolTipLabel: ReactNode = null;
  if (activePoint) {
    const start = DateTime.fromJSDate(activePoint.start);
    const startStr = start.toLocaleString(DateTime.TIME_WITH_SECONDS);
    const end = start.plus({ seconds: props.trend.bucketSize });
    const endStr = end.toLocaleString(DateTime.TIME_WITH_SECONDS);
    toolTipLabel = (
      <Box>
        <Box>
          {startStr} - {endStr}
        </Box>
        <Box>{activePoint.count} occurrences</Box>
      </Box>
    );
  }

  return (
    <Tooltip label={toolTipLabel}>
      <div>
        <Bar
          type="bar"
          data={data}
          options={options}
          height={27}
          width={94}
          className={styles.trendCell}
        />
      </div>
    </Tooltip>
  );
}
