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

const ChartExample = () => {
  const [options, setOptions] = useState<AgFinancialChartOptions>({
    data: getData(),
    title: {
      text: "Customisation",
    },
    rangeButtons: false,
    theme: {
      overrides: {
        common: {
          annotations: {
            line: {
              stroke: "lime",
              strokeWidth: 3,
              lineDash: [3, 4],
            },
            "parallel-channel": {
              stroke: "red",
              strokeWidth: 4,
              background: {
                fill: "red",
              },
              middle: {
                strokeOpacity: 0,
              },
            },
            comment: {
              fill: "orange",
              color: "blue",
              stroke: "blue",
              strokeWidth: 2,
            },
          },
        },
      },
    },
    initialState: {
      annotations: [
        {
          type: "parallel-channel",
          height: 83.55795148247944,
          start: {
            x: {
              __type: "date",
              value: "Tue Sep 19 2023 00:00:00 GMT+0100 (British Summer Time)",
            },
            y: 4401.88679245283,
          },
          end: {
            x: {
              __type: "date",
              value: "Thu Oct 05 2023 00:00:00 GMT+0100 (British Summer Time)",
            },
            y: 4279.245283018868,
          },
        },
        {
          type: "line",
          start: {
            x: {
              __type: "date",
              value: "Tue Sep 05 2023 00:00:00 GMT+0100 (British Summer Time)",
            },
            y: 4507.681940700809,
          },
          end: {
            x: {
              __type: "date",
              value: "Fri Oct 13 2023 00:00:00 GMT+0100 (British Summer Time)",
            },
            y: 4331.805929919137,
          },
        },
        {
          type: "comment",
          text: "Comment",
          visible: true,
          x: {
            __type: "date",
            value: "Tue Aug 22 2023 00:00:00 GMT+0100 (British Summer Time)",
          },
          y: 4261.725067385445,
        },
      ],
    },
  });

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