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

const dateFormatter = new Intl.DateTimeFormat("en-US", {
  day: "numeric",
  month: "short",
  year: "numeric",
});
const numberFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
});

const ChartExample = () => {
  const [options, setOptions] = useState<AgCartesianChartOptions>({
    title: {
      text: "Market Data",
    },
    subtitle: {
      text: "Last 5 years",
    },
    data: data,
    series: [
      {
        type: "line",
        xKey: "date",
        yKey: "AAPL",
        marker: {
          enabled: false,
        },
      },
      {
        type: "line",
        xKey: "date",
        yKey: "MSFT",
        marker: {
          enabled: false,
        },
      },
      {
        type: "line",
        xKey: "date",
        yKey: "AMZN",
        marker: {
          enabled: false,
        },
      },
    ],
    axes: [
      {
        type: "time",
        position: "bottom",
        nice: false,
        interval: {
          maxSpacing: 200,
        },
        crosshair: {
          label: {
            renderer: ({ value }) => {
              return { text: dateFormatter.format(value) };
            },
          },
        },
      },
      {
        type: "number",
        position: "left",
        label: {
          formatter: (params) => numberFormatter.format(+params.value),
        },
      },
    ],
    legend: {
      enabled: true,
    },
    navigator: {
      enabled: true,
      height: 40,
      miniChart: {
        enabled: true,
        label: {
          fontSize: 20,
          fontWeight: "bold",
        },
      },
    },
    zoom: {
      enabled: true,
    },
    initialState: {
      zoom: {
        ratioX: { start: 0.9, end: 1 },
      },
    },
  });

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