import React, { useState, Fragment } from "react";
import { createRoot } from "react-dom/client";
import { AgCharts } from "ag-charts-react";
import { AgChartOptions } from "ag-charts-enterprise";
import { AAPL, MSFT } from "./data";
import "ag-charts-enterprise";

const commonOptions: AgChartOptions = {
  minWidth: 0,
  minHeight: 0,
  series: [
    {
      type: "line",
      xKey: "date",
      yKey: "value",
    },
  ],
  sync: {
    enabled: true,
    axes: "x",
    nodeInteraction: true,
  },
  zoom: {
    enabled: true,
    enableSelecting: true,
  },
  axes: [
    {
      type: "time",
      position: "bottom",
      nice: false,
      interval: {
        maxSpacing: 180,
      },
      crosshair: {
        label: {
          format: "%d %b %Y",
        },
      },
    },
    {
      type: "number",
      position: "left",
      label: {
        format: "$~s",
      },
    },
  ],
};

const MyChart1 = () => {
  const [chartOptions1, setChartOptions1] = useState<AgChartOptions>({
    ...commonOptions,

    data: AAPL,
    title: {
      text: "Apple (AAPL)",
      textAlign: "left",
    },
  });

  return <AgCharts options={chartOptions1 as any} />;
};

const MyChart2 = () => {
  const [chartOptions2, setChartOptions2] = useState<AgChartOptions>({
    ...commonOptions,

    data: MSFT,
    title: {
      text: "Microsoft (MSFT)",
      textAlign: "left",
    },
    navigator: {
      enabled: true,
    },
    initialState: {
      zoom: {
        ratioX: { start: 0.8, end: 1 },
      },
    },
  });

  return <AgCharts options={chartOptions2 as any} />;
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <Fragment>
    <MyChart1 />
    <MyChart2 />
  </Fragment>,
);

/** 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 **/
