import React, { useState, Fragment } from "react";
import { createRoot } from "react-dom/client";
import { AgGauge } from "ag-charts-react";
import {
  AgLinearGaugeLabelPlacement,
  AgLinearGaugeOptions,
} from "ag-charts-enterprise";
import "ag-charts-enterprise";
import clone from "clone";

const placementColors: Record<AgLinearGaugeLabelPlacement, string> = {
  "inside-start": "white",
  "outside-start": "#888",
  "inside-end": "#888",
  "outside-end": "#888",
  "inside-center": "white",
  "bar-inside": "white",
  "bar-inside-end": "white",
  "bar-outside-end": "#888",
  "bar-end": "white",
};

const ChartExample = () => {
  const [options, setOptions] = useState<AgLinearGaugeOptions>({
    type: "linear-gauge",

    direction: "horizontal",
    value: 50,
    scale: {
      min: 0,
      max: 100,
      label: {
        enabled: false,
      },
    },
    label: {
      enabled: true,
      placement: "inside-start",
      avoidCollisions: true,
    },
  });

  const setLabelPlacement = (placement: AgLinearGaugeLabelPlacement) => {
    const nextOptions = clone(options);

    nextOptions.label!.placement = placement;
    nextOptions.label!.color = placementColors[placement];

    setOptions(nextOptions);
  };

  const setAvoidCollisions = (avoidCollisions: boolean) => {
    const nextOptions = clone(options);

    nextOptions.label!.avoidCollisions = avoidCollisions;

    setOptions(nextOptions);
  };

  const setValue = (value: number) => {
    const nextOptions = clone(options);

    nextOptions.value = value;

    setOptions(nextOptions);
  };

  return (
    <Fragment>
      <div className="toolbar">
        Placement:
        <select onChange={(event) => setLabelPlacement(event.target.value)}>
          <option value="inside-start" selected={true}>
            Inside Start
          </option>
          <option value="outside-start">Outside Start</option>
          <option value="inside-end">Inside End</option>
          <option value="outside-end">Outside End</option>
          <option value="inside-center">Inside Center</option>
          <option value="bar-inside">Bar Inside</option>
          <option value="bar-inside-end">Bar Inside End</option>
          <option value="bar-outside-end">Bar Outside End</option>
          <option value="bar-end">Bar End</option>
        </select>
        Avoid Collisions:
        <select
          onChange={(event) => setAvoidCollisions(event.target.value === "on")}
        >
          <option value="on" selected={true}>
            On
          </option>
          <option value="off">Off</option>
        </select>
        Value:
        <select onChange={(event) => setValue(Number(event.target.value))}>
          <option value="1">1</option>
          <option value="50" selected={true}>
            50
          </option>
          <option value="99">99</option>
        </select>
      </div>
      <AgGauge options={options as any} />
    </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 **/
