import React, { useState, Fragment } from "react";
import { createRoot } from "react-dom/client";
import { AgCharts } from "ag-charts-react";
import { AgPolarChartOptions } from "ag-charts-community";
import { getData } from "./data";
import clone from "clone";

const ChartExample = () => {
  const [options, setOptions] = useState<AgPolarChartOptions>({
    data: getData(),
    series: [
      {
        type: "pie",
        angleKey: "value",
        calloutLabelKey: "label",
      },
    ],
    legend: {
      maxHeight: 200,
      item: {
        maxWidth: 130,
        paddingX: 32,
        paddingY: 8,
        marker: {
          padding: 8,
        },
      },
    },
  });

  const updateLegendItemPaddingX = (event: any) => {
    const nextOptions = clone(options);

    var value = +event.target.value;
    nextOptions.legend!.item!.paddingX = value;

    document.getElementById("xPaddingValue")!.innerHTML = String(value);

    setOptions(nextOptions);
  };

  const updateLegendItemPaddingY = (event: any) => {
    const nextOptions = clone(options);

    var value = event.target.value;
    nextOptions.legend!.item!.paddingY = +event.target.value;

    document.getElementById("yPaddingValue")!.innerHTML = String(value);

    setOptions(nextOptions);
  };

  const updateLegendItemSpacing = (event: any) => {
    const nextOptions = clone(options);

    var value = +event.target.value;
    nextOptions.legend!.item!.marker!.padding = value;

    document.getElementById("markerPaddingValue")!.innerHTML = String(value);

    setOptions(nextOptions);
  };

  const updateLegendItemMaxWidth = (event: any) => {
    const nextOptions = clone(options);

    var value = +event.target.value;
    nextOptions.legend!.item!.maxWidth = value;

    document.getElementById("maxWidthValue")!.innerHTML = String(value);

    setOptions(nextOptions);
  };

  return (
    <Fragment>
      <div className="toolbar">
        <div className="sliders">
          <label htmlFor="xPaddingLabel">item.paddingX</label>
          <input
            type="range"
            id="xPaddingLabel"
            min="0"
            max="50"
            defaultValue="32"
            onInput={(event) => updateLegendItemPaddingX(event)}
            onChange={(event) => updateLegendItemPaddingX(event)}
          />
          <span id="xPaddingValue" className="slider-value">
            32
          </span>
          <label htmlFor="yPaddingLabel">item.paddingY</label>
          <input
            type="range"
            id="yPaddingLabel"
            min="0"
            max="30"
            defaultValue="8"
            onInput={(event) => updateLegendItemPaddingY(event)}
            onChange={(event) => updateLegendItemPaddingY(event)}
          />
          <span id="yPaddingValue" className="slider-value">
            8
          </span>
          <label htmlFor="markerPaddingLabel">item.marker.padding</label>
          <input
            type="range"
            id="markerPaddingLabel"
            min="0"
            max="30"
            defaultValue="8"
            onInput={(event) => updateLegendItemSpacing(event)}
            onChange={(event) => updateLegendItemSpacing(event)}
          />
          <span id="markerPaddingValue" className="slider-value">
            8
          </span>
          <label htmlFor="maxWidthLabel">item.maxWidth</label>
          <input
            type="range"
            id="maxWidthLabel"
            min="0"
            max="130"
            defaultValue="130"
            onInput={(event) => updateLegendItemMaxWidth(event)}
            onChange={(event) => updateLegendItemMaxWidth(event)}
          />
          <span id="maxWidthValue" className="slider-value">
            130
          </span>
        </div>
      </div>
      <AgCharts options={options} className="chart" />
    </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 **/
