import React from "react";

import { styled, useTheme } from "@mui/material/styles";
import { ChartsLegendProps } from "@mui/x-charts/ChartsLegend";
import { DatasetType, MakeOptional } from "@mui/x-charts/internals";
import { LineChart as MuiLineChart } from "@mui/x-charts/LineChart";
import { LineSeriesType } from "@mui/x-charts/models/seriesType";

import { Granularity } from "../../types/dashboard";
import { getDateValueFormatter } from "../../util/timeline";

declare module "@mui/material/styles" {
  interface Palette {
    graphColorPrimary?: { main: string };
  }
}

const StyledLineChart = styled(MuiLineChart, {
  name: "BananasChart",
  slot: "Chart",
})(({ theme }) =>
  theme.unstable_sx({
    ".MuiChartsAxis-line, .MuiChartsAxis-tick": {
      opacity: 0,
      stroke: theme.palette.divider,
    },
  }),
);

export interface LineChartProps {
  dataset: DatasetType;
  series?: MakeOptional<LineSeriesType, "type">[];
  dataKeyX: string;
  dataKeyY?: string;
  height?: number;
  area?: boolean;
  granularity?: Granularity;
  yAxisOptions?: object;
  legendProps?: ChartsLegendProps;
}

export const LineChart: React.FC<LineChartProps> = ({
  dataset,
  series,
  dataKeyX,
  dataKeyY,
  height = 300,
  area,
  granularity = "day",
  yAxisOptions,
  legendProps,
}) => {
  const theme = useTheme();

  return (
    <StyledLineChart
      dataset={dataset}
      grid={{ horizontal: true }}
      height={height}
      series={
        series ?? [
          {
            dataKey: dataKeyY,
            showMark: false,
            curve: "monotoneX",
            color: theme.palette.graphColorPrimary?.main ?? theme.palette.primary.main,
            area,
          },
        ]
      }
      slotProps={{
        legend: {
          direction: "row",
          position: { vertical: "top", horizontal: "middle" },
          padding: 0,
          itemMarkWidth: 10,
          itemMarkHeight: 10,
          itemGap: 15,
          labelStyle: {
            fontSize: "0.8rem",
          },
          ...legendProps,
        },
        // TODO: Make line dashed between point and "today"-point, i.e. "forcast"
        // line: {
        //   limit: 5,
        //   sxAfter: {
        //     strokeDasharray: "10 5",
        //   },
        // } as any,
      }}
      xAxis={[
        {
          dataKey: dataKeyX,
          tickNumber: 1,
          scaleType: "point",
          valueFormatter: getDateValueFormatter(granularity),
        },
      ]}
      yAxis={[
        {
          min: 0,
          tickNumber: 4,
          tickMinStep: 1,
          ...yAxisOptions,
        },
      ]}
    />
  );
};

export default LineChart;
