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

const ChartExample = () => {
  const [options, setOptions] = useState<AgCartesianChartOptions>({
    title: {
      text: `Renewable sources used to generate electricity for transport fuels`,
    },
    data: getData(),
    series: [
      {
        type: "line",
        xKey: "year",
        yKey: "Onshore wind",
        yName: "Onshore Wind",
      },
      {
        type: "line",
        xKey: "year",
        yKey: "Offshore wind",
        yName: "Offshore Wind",
      },
      {
        type: "line",
        xKey: "year",
        yKey: "Marine energy",
        yName: "Marine Energy",
      },
      {
        type: "line",
        xKey: "year",
        yKey: "Solar photovoltaics",
        yName: "Solar Photovoltaics",
      },
      {
        type: "line",
        xKey: "year",
        yKey: "Small scale Hydro",
        yName: "Small Scale Hydro",
      },
      {
        type: "line",
        xKey: "year",
        yKey: "Large scale Hydro",
        yName: "Large Scale Hydro",
      },
      {
        type: "line",
        xKey: "year",
        yKey: "Plant biomass",
        yName: "Plant Biomass",
      },
      {
        type: "line",
        xKey: "year",
        yKey: "Animal biomass",
        yName: "Animal Biomass",
      },
      {
        type: "line",
        xKey: "year",
        yKey: "Landfill gas",
        yName: "Landfill Gas",
      },
      {
        type: "line",
        xKey: "year",
        yKey: "Sewage gas",
        yName: "Sewage Gas",
      },
    ],
    axes: [
      {
        position: "bottom",
        type: "time",
        gridLine: {
          style: [],
        },
        nice: false,
      },
      {
        position: "right",
        type: "number",
        title: {
          text: `kilotonnes of oil equivalent (ktoe)`,
        },
        label: {
          formatter: (params) => `${params.value / 1000}K`,
        },
        line: {
          enabled: false,
        },
      },
    ],
    legend: {
      maxHeight: 40,
      maxWidth: 800,
      pagination: {
        marker: {
          size: 10,
        },
        activeStyle: {
          fill: "#284E8F",
        },
        inactiveStyle: {
          fillOpacity: 0.5,
        },
        highlightStyle: {
          fill: "#7BAFDF",
        },
        label: {
          color: "rgb(87, 87, 87)",
        },
      },
    },
  });

  const updateLegendPosition = (value: AgChartLegendPosition) => {
    const nextOptions = clone(options);

    nextOptions.legend!.position = value;
    switch (value) {
      case "top":
      case "bottom":
        nextOptions.legend!.maxHeight = 40;
        nextOptions.legend!.maxWidth = 800;
        break;
      case "right":
      case "left":
        nextOptions.legend!.maxHeight = 200;
        nextOptions.legend!.maxWidth = 200;
        break;
    }

    setOptions(nextOptions);
  };

  return (
    <Fragment>
      <div className="toolbar">
        Legend Position:
        <button
          className="button--code"
          onClick={() => updateLegendPosition("right")}
        >
          'right'
        </button>
        <button
          className="button--code"
          onClick={() => updateLegendPosition("bottom")}
        >
          'bottom'
        </button>
        <button
          className="button--code"
          onClick={() => updateLegendPosition("left")}
        >
          'left'
        </button>
        <button
          className="button--code"
          onClick={() => updateLegendPosition("top")}
        >
          'top'
        </button>
      </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 **/
