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

const ChartExample = () => {
  const [options, setOptions] = useState<AgChartOptions>({
    data: getData(),
    title: {
      text: "Monthly Sales Revenue",
    },
    footnote: {
      text: "2024, values in $1000s",
    },
    series: [
      {
        type: "line",
        xKey: "month",
        yKey: "revenue",
        interpolation: { type: "smooth" },
        marker: {
          enabled: false,
        },
        label: {
          enabled: true,
        },
      },
    ],
    annotations: {
      enabled: true,
    },
    initialState: {
      annotations: [
        {
          type: "comment",
          x: { value: "May", groupPercentage: 0.2 },
          y: 98,
          text: "Sales increased\nsignificantly\nin May",
          fontSize: 12,
        },
        {
          type: "vertical-line",
          value: "May",
          lineStyle: "dotted",
        },
        {
          type: "vertical-line",
          value: "Sep",
          lineStyle: "dotted",
        },
        {
          type: "callout",
          start: {
            x: { value: "Sep", groupPercentage: 0.1 },
            y: 80,
          },
          end: {
            x: { value: "Sep", groupPercentage: 0.5 },
            y: 55,
          },
          text: "End of summer\ndip recovered",
          fontSize: 12,
        },
        {
          type: "horizontal-line",
          value: 72,
          axisLabel: {
            fillOpacity: 0.5,
          },
          lineStyle: "dotted",
        },
        {
          type: "line",
          start: { x: "Jan", y: 32 },
          end: { x: "Dec", y: 105 },
        },
        {
          type: "parallel-channel",
          height: 13,
          start: {
            x: {
              value: "Mar",
              groupPercentage: 0.08,
            },
            y: 44.7,
          },
          end: {
            x: {
              value: "Jun",
              groupPercentage: -0.08,
            },
            y: 86.2,
          },
          strokeOpacity: 0,
        },
        {
          type: "parallel-channel",
          height: 13,
          start: {
            x: {
              value: "Aug",
              groupPercentage: 0.08,
            },
            y: 78.7,
          },
          end: {
            x: {
              value: "Oct",
              groupPercentage: -0.08,
            },
            y: 101.5,
          },
          strokeOpacity: 0,
        },
      ],
    },
  });

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

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