import React, { useState, Fragment } from "react";
import { createRoot } from "react-dom/client";
import { AgCharts } from "ag-charts-react";
import { AgCartesianChartOptions } from "ag-charts-community";
import clone from "clone";

const selectedMonths = new Set<string>();
function getData() {
  return [
    {
      month: "March",
      units: 25,
      brands: { BMW: 10, Toyota: 15 },
      selected: selectedMonths.has("March"),
    },
    {
      month: "April",
      units: 27,
      brands: { Ford: 17, BMW: 10 },
      selected: selectedMonths.has("April"),
    },
    {
      month: "May",
      units: 42,
      brands: { Nissan: 20, Toyota: 22 },
      selected: selectedMonths.has("May"),
    },
  ];
}

const ChartExample = () => {
  const [options, setOptions] = useState<AgCartesianChartOptions>({
    title: {
      text: "Number of Cars Sold",
    },
    subtitle: {
      text: "(click a marker to toggle its selected state)",
    },
    data: getData(),
    series: [
      {
        type: "line",
        xKey: "month",
        yKey: "units",
        listeners: {
          nodeClick: (event: any) => {
            toggleDatum(event, event.datum);
          },
        },
        marker: {
          size: 16,
          itemStyler: (params) => {
            // Use a different size and color for selected nodes.
            if (params.datum.selected) {
              return {
                fill: "red",
                size: 24,
              };
            }
          },
        },
        cursor: "pointer",
      },
    ],
    axes: [
      {
        type: "category",
        position: "bottom",
      },
      {
        type: "number",
        position: "left",
      },
    ],
  });

  const toggleDatum = (_event: any, datum?: any) => {
    const nextOptions = clone(options);

    if (datum == null) {
      selectedMonths.clear();
    } else if (selectedMonths.has(datum.month)) {
      selectedMonths.delete(datum.month);
    } else {
      selectedMonths.add(datum.month);
    }
    nextOptions.data = getData();

    setOptions(nextOptions);
  };

  return (
    <Fragment>
      <div className="toolbar">
        <button onClick={toggleDatum}>Reset</button>
      </div>
      <AgCharts options={options} />
    </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 **/
