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

function initAnimation() {
  const f = () => {
    (document.querySelector(".gesture-demo") as HTMLElement).style.display =
      "none";
  };
  document.addEventListener("touchstart", f, { capture: true, once: true });
  document.addEventListener("wheel", f, { capture: true, once: true });
  document.addEventListener("mousedown", f, { capture: true, once: true });
  document.addEventListener("keydown", f, { capture: true, once: true });
  return { enabled: false };
}

const ChartExample = () => {
  const [options, setOptions] = useState<AgCartesianChartOptions>({
    title: {
      text: "Financial Performance Overview",
    },
    animation: initAnimation(),
    data: [
      {
        year: 2018,
        revenue: 120,
        expenses: 80,
        profit: 40,
        investments: 30,
        taxes: 20,
        dividends: 10,
        rAndD: 25,
      },
      {
        year: 2019,
        revenue: 140,
        expenses: 90,
        profit: 50,
        investments: 40,
        taxes: 25,
        dividends: 12,
        rAndD: 30,
      },
      {
        year: 2020,
        revenue: 160,
        expenses: 100,
        profit: 60,
        investments: 50,
        taxes: 30,
        dividends: 15,
        rAndD: 35,
      },
      {
        year: 2021,
        revenue: 180,
        expenses: 110,
        profit: 70,
        investments: 55,
        taxes: 35,
        dividends: 18,
        rAndD: 40,
      },
      {
        year: 2022,
        revenue: 200,
        expenses: 120,
        profit: 80,
        investments: 60,
        taxes: 40,
        dividends: 20,
        rAndD: 45,
      },
    ],
    series: [
      { type: "line", xKey: "year", yKey: "revenue", yName: "Revenue" },
      { type: "line", xKey: "year", yKey: "expenses", yName: "Expenses" },
      { type: "line", xKey: "year", yKey: "profit", yName: "Profit" },
      { type: "line", xKey: "year", yKey: "investments", yName: "Investments" },
      { type: "line", xKey: "year", yKey: "taxes", yName: "Taxes" },
      { type: "line", xKey: "year", yKey: "dividends", yName: "Dividends" },
      { type: "line", xKey: "year", yKey: "rAndD", yName: "R&D Spending" },
    ],
  });

  return (
    <Fragment>
      <div className="toolbar"></div>

      <AgCharts options={options as any} />
      <div className="gesture-demo">
        <div className="finger"></div>
      </div>
    </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 **/
