import React, { useState, Fragment } from "react";
import { createRoot } from "react-dom/client";
import { AgCharts } from "ag-charts-react";
import { AgCartesianChartOptions } from "ag-charts-community";
import {
  AgTooltipAnchorTo,
  AgTooltipPlacement,
} from "../../../../../../../ag-charts-types/dist/types/src/chart/tooltipOptions";
import { getData } from "./data";
import clone from "clone";

const ChartExample = () => {
  const [options, setOptions] = useState<AgCartesianChartOptions>({
    data: getData(),
    series: [
      {
        type: "line",
        xKey: "month",
        yKey: "sweaters",
        yName: "Sweaters Made",
      },
    ],
    tooltip: {
      position: {},
    },
  });

  const setAnchorTo = (anchorTo: AgTooltipAnchorTo) => {
    const nextOptions = clone(options);

    nextOptions.tooltip!.position!.anchorTo = anchorTo;

    setOptions(nextOptions);
  };

  const setPlacement = (placement: string) => {
    const nextOptions = clone(options);

    nextOptions.tooltip!.position!.placement = placement.split(
      /,\s+/g,
    ) as AgTooltipPlacement[];

    setOptions(nextOptions);
  };

  return (
    <Fragment>
      <div className="toolbar">
        <span>Anchor to:</span>
        <select onChange={(event) => setAnchorTo(event.target.value)}>
          <option value="node" selected={true}>
            Node
          </option>
          <option value="pointer">Pointer</option>
          <option value="chart">Chart</option>
        </select>
        <span>Placement:</span>
        <select onChange={(event) => setPlacement(event.target.value)}>
          <option value="top" selected={true}>
            Top
          </option>
          <option value="top-right">Top Right</option>
          <option value="right">Right</option>
          <option value="bottom-right">Bottom Right</option>
          <option value="bottom">Bottom</option>
          <option value="bottom-left">Bottom Left</option>
          <option value="left">Left</option>
          <option value="top-left">Top Left</option>

          <option value="left, right">Left + Right fallback</option>
          <option value="right, left">Right + Left fallback</option>
        </select>
      </div>
      <AgCharts options={options} />
    </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 **/
