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

const data = getData();
const bar = ({ x, y, path, size }: AgMarkerShapeFnParams) => {
  const halfSize = size / 2;
  path.rect(x - halfSize / 2, y - halfSize, halfSize, size);
};

const ChartExample = () => {
  const [options, setOptions] = useState<AgCartesianChartOptions>({
    data,
    title: {
      text: "The Technology Industry",
    },
    padding: {
      left: 40,
      right: 40,
    },
    theme: {
      overrides: {
        common: {
          legend: {
            item: {
              marker: {
                shape: bar,
                strokeWidth: 0,
              },
              line: {
                strokeWidth: 0,
              },
            },
          },
          axes: {
            "grouped-category": {
              groupPaddingInner: 0,
              paddingInner: 0.4,
            },
            number: {
              line: {
                enabled: true,
              },
              tick: {
                enabled: true,
              },
            },
          },
        },
        bar: {
          series: {
            fillOpacity: 0.4,
          },
        },
        line: {
          series: {
            marker: {
              shape: bar,
              size: 10,
            },
          },
        },
      },
    },
    series: [
      {
        type: "line",
        xKey: "location",
        xName: "Location",
        yKey: "startups",
        yName: "Startups",
      },
      {
        type: "line",
        xKey: "location",
        xName: "Location",
        yKey: "techCompanies",
        yName: "Tech Companies",
      },
      {
        type: "scatter",
        xKey: "location",
        xName: "Location",
        yKey: "funding",
        yName: "Funding",
        fillOpacity: 1,
      },
      {
        type: "scatter",
        xKey: "location",
        xName: "Location",
        yKey: "employees",
        yName: "Employees",
        fillOpacity: 1,
      },
      {
        type: "bar",
        xKey: "location",
        xName: "Location",
        yKey: "researchInstitutions",
        yName: "Research Institutions",
      },
    ],
    axes: [
      {
        position: "left",
        type: "number",
        keys: ["startups", "techCompanies"],
        title: {
          text: "Startups and Tech Companies",
        },
      },
      {
        position: "left",
        type: "number",
        keys: ["employees"],
        title: {
          text: "Number of Employees",
        },
      },
      {
        position: "left",
        type: "number",
        keys: ["funding"],
        title: {
          text: "Funding",
        },
      },
      {
        position: "right",
        type: "number",
        keys: ["researchInstitutions"],
        title: {
          text: "Number of Institutions",
        },
      },
      {
        position: "top",
        type: "grouped-category",
      },
    ],
    annotations: {
      enabled: true,
    },
  });

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