import React, { useState, Fragment } from "react";
import { createRoot } from "react-dom/client";
import { AgCharts } from "ag-charts-react";
import {
  AgCartesianChartOptions,
  AgCartesianSeriesTooltipRendererParams,
  AgChartOptions,
  AgPolarChartOptions,
  AgTooltipRendererResult,
} from "ag-charts-enterprise";
import { getData } from "./data";
import "ag-charts-enterprise";
import clone from "clone";

const numFormatter = new Intl.NumberFormat("en-US");
const tooltip = {
  renderer: ({
    datum,
    yKey,
    yName,
  }: AgCartesianSeriesTooltipRendererParams): AgTooltipRendererResult => ({
    data: [{ label: yName!, value: numFormatter.format(datum[yKey]) }],
  }),
};
const barOptions: AgCartesianChartOptions = {
  series: [
    {
      type: "bar",
      xKey: "station",
      yKey: "early",
      stacked: true,
      yName: "Early",
      tooltip,
    },
    {
      type: "bar",
      xKey: "station",
      yKey: "morningPeak",
      yName: "Morning peak",
      stacked: true,
      tooltip,
    },
    {
      type: "bar",
      xKey: "station",
      yKey: "interPeak",
      yName: "Between peak",
      stacked: true,
      tooltip,
    },
    {
      type: "bar",
      xKey: "station",
      yKey: "afternoonPeak",
      yName: "Afternoon peak",
      stacked: true,
      tooltip,
    },
    {
      type: "bar",
      xKey: "station",
      yKey: "evening",
      yName: "Evening",
      stacked: true,
      tooltip,
    },
  ],
  axes: [
    {
      type: "category",
      position: "bottom",
    },
    {
      type: "number",
      position: "left",
      label: {
        formatter: (params) => {
          return params.value / 1000 + "k";
        },
      },
    },
  ],
};
const lineOptions: AgCartesianChartOptions = {
  series: [
    {
      type: "line",
      xKey: "station",
      yKey: "early",
      yName: "Early",
      tooltip,
    },
    {
      type: "line",
      xKey: "station",
      yKey: "morningPeak",
      yName: "Morning peak",
      tooltip,
    },
    {
      type: "line",
      xKey: "station",
      yKey: "interPeak",
      yName: "Between peak",
      tooltip,
    },
    {
      type: "line",
      xKey: "station",
      yKey: "afternoonPeak",
      yName: "Afternoon peak",
      tooltip,
    },
    {
      type: "line",
      xKey: "station",
      yKey: "evening",
      yName: "Evening",
      tooltip,
    },
  ],
  axes: [
    {
      type: "category",
      position: "bottom",
    },
    {
      type: "number",
      position: "left",
      label: {
        formatter: (params) => {
          return params.value / 1000 + "k";
        },
      },
    },
  ],
};
const areaOptions: AgCartesianChartOptions = {
  series: [
    {
      type: "area",
      xKey: "station",
      yKey: "early",
      stacked: true,
      yName: "Early",
      tooltip,
    },
    {
      type: "area",
      xKey: "station",
      yKey: "morningPeak",
      yName: "Morning peak",
      stacked: true,
      tooltip,
    },
    {
      type: "area",
      xKey: "station",
      yKey: "interPeak",
      yName: "Between peak",
      stacked: true,
      tooltip,
    },
    {
      type: "area",
      xKey: "station",
      yKey: "afternoonPeak",
      yName: "Afternoon peak",
      stacked: true,
      tooltip,
    },
    {
      type: "area",
      xKey: "station",
      yKey: "evening",
      yName: "Evening",
      stacked: true,
      tooltip,
    },
  ],
  axes: [
    {
      type: "category",
      position: "bottom",
    },
    {
      type: "number",
      position: "left",
      label: {
        formatter: (params) => {
          return params.value / 1000 + "k";
        },
      },
    },
  ],
};
const donutOptions: AgPolarChartOptions = {
  series: [
    {
      type: "pie",
      title: {
        text: "Morning Peak",
      },
      calloutLabelKey: "station",
      legendItemKey: "station",
      angleKey: "morningPeak",
      outerRadiusRatio: 0.6,
    },
    {
      type: "donut",
      title: {
        text: "Afternoon Peak",
      },
      calloutLabelKey: "station",
      legendItemKey: "station",
      angleKey: "afternoonPeak",
      showInLegend: false,
    },
  ],
  axes: [],
};

const ChartExample = () => {
  const [options, setOptions] = useState<
    AgCartesianChartOptions | AgPolarChartOptions
  >({
    data: getData(),
    animation: {
      enabled: true,
    },
    ...barOptions,
  });

  const changeSeriesBar = () => {
    const nextOptions = clone(options);

    nextOptions.series = barOptions.series;
    nextOptions.axes = barOptions.axes;

    setOptions(nextOptions);
  };

  const changeSeriesLine = () => {
    const nextOptions = clone(options);

    nextOptions.series = lineOptions.series;
    nextOptions.axes = lineOptions.axes;

    setOptions(nextOptions);
  };

  const changeSeriesArea = () => {
    const nextOptions = clone(options);

    nextOptions.series = areaOptions.series;
    nextOptions.axes = areaOptions.axes;

    setOptions(nextOptions);
  };

  const changeSeriesDonut = () => {
    const nextOptions = clone(options);

    nextOptions.series = donutOptions.series;
    nextOptions.axes = donutOptions.axes;

    setOptions(nextOptions);
  };

  const changeDuration = (duration: number) => {
    const nextOptions = clone(options);

    nextOptions.animation = { duration };

    setOptions(nextOptions);
  };

  return (
    <Fragment>
      <div className="toolbar">
        <button onClick={changeSeriesBar}>Bar</button>
        <button onClick={changeSeriesLine}>Line</button>
        <button onClick={changeSeriesArea}>Area</button>
        <button onClick={changeSeriesDonut}>Pie &amp; Donut</button>
        <hr />
        <button onClick={() => changeDuration(500)}>Duration: 500ms</button>
        <button onClick={() => changeDuration(2000)}>Duration: 2000ms</button>
      </div>
      <AgCharts options={options as any} />
    </Fragment>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(<ChartExample />);

/** DARK MODE START **/
import { AgCharts as __chartAPI } from "ag-charts-community";

let darkmode =
  (localStorage["documentation:darkmode"] ||
    String(matchMedia("(prefers-color-scheme: dark)").matches)) === "true";

const isAgThemeOrUndefined = (theme) => {
  return (
    theme == null || (typeof theme === "string" && theme.startsWith("ag-"))
  );
};

const getDarkmodeTheme = (theme = "ag-default", preset) => {
  const baseTheme =
    preset === "price-volume" ? "ag-financial" : theme.replace(/-dark$/, "");
  return darkmode ? baseTheme + "-dark" : baseTheme;
};

__chartAPI.optionsMutationFn = function update(options, preset) {
  const nextOptions = { ...options };
  const theme = options.theme;
  if (isAgThemeOrUndefined(theme)) {
    nextOptions.theme = getDarkmodeTheme(theme, preset);
  } else if (
    typeof theme === "object" &&
    isAgThemeOrUndefined(theme.baseTheme)
  ) {
    nextOptions.theme = {
      ...options.theme,
      baseTheme: getDarkmodeTheme(theme.baseTheme, preset),
    };
  }
  return nextOptions;
};

const applyDarkmode = () => {
  document.documentElement.setAttribute("data-dark-mode", darkmode);
  const charts = document.querySelectorAll("[data-ag-charts]");
  charts.forEach((element) => {
    const chart = __chartAPI.getInstance(element.parentElement);
    if (chart == null) return;
    // This is just needed to trigger the theme update
    chart.update(chart.getOptions());
  });
  return charts.length !== 0;
};

if (!applyDarkmode()) {
  /* React defers updates. Rather than try and hook into the API, just wait until the darkmode is applied. */
  const observer = new MutationObserver(() => {
    if (applyDarkmode()) {
      observer.disconnect();
    }
  });
  observer.observe(document.body, {
    attributes: true,
    childList: true,
    subtree: true,
  });
}
window.addEventListener("message", (event) => {
  if (event.data && event.data.type === "color-scheme-change") {
    darkmode = event.data.darkmode;
    applyDarkmode();
  }
});
/** DARK MODE END **/
