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

const ChartExample = () => {
  const [options, setOptions] = useState<AgChartOptions>({
    data: getData(),
    title: {
      text: "Smartphone Production Cost Vs Retail Price",
    },
    subtitle: {
      text: "Production cost range vs retail price range of top-selling phone brands on the market in 2023",
      spacing: 30,
    },
    footnote: {
      text: "Costs include essential components like core processors, display, memory, and camera module but exclude marketing, research, distribution, staff, accessories, packaging, and software.",
      spacing: 30,
    },
    series: [
      {
        type: "range-bar",
        direction: "horizontal",
        xKey: "smartphone",
        xName: "Smartphone",
        yLowKey: "lowCost",
        yHighKey: "highCost",
        yLowName: "Lowest Cost",
        yHighName: "Highest Cost",
        yName: "Production Cost Range",
        fill: "#D1C0A8",
        stroke: "#D1C0A8",
      },
      {
        type: "range-bar",
        direction: "horizontal",
        xKey: "smartphone",
        xName: "Smartphone",
        yLowKey: "lowRetail",
        yHighKey: "highRetail",
        yLowName: "Lowest Price",
        yHighName: "Highest Price",
        yName: "Retail Price Range",
        fill: "#205C37",
        stroke: "#205C37",
      },
      {
        type: "bubble",
        yKey: "smartphone",
        xKey: "profitMargin",
        xName: "Profit Margin",
        yName: "Profit Margin %",
        sizeKey: "profitMargin",
        labelKey: "profitMargin",
        label: {
          formatter: ({ value }) => `${Number(value).toFixed(0)}%`,
        },
        fill: "#ced1a8",
        stroke: "#205C37",
        strokeWidth: 1,
        maxSize: 50,
        size: 15,
      },
    ],
    axes: [
      {
        type: "category",
        position: "left",
        keys: ["smartphone"],
        groupPaddingInner: 0,
        paddingInner: 0.9,
        paddingOuter: 0.8,
      },
      {
        type: "number",
        position: "top",
        keys: ["profitMargin"],
        label: {
          formatter: ({ value }) => `${value}%`,
        },
        line: {
          enabled: false,
        },
      },
      {
        type: "number",
        position: "bottom",
        keys: ["lowRetail", "highRetail", "lowCost", "highCost"],
        label: {
          formatter: ({ value }) =>
            `${Number(value).toLocaleString("en-US", {
              style: "currency",
              currency: "USD",
              maximumFractionDigits: 0,
            })}`,
        },
        line: {
          enabled: false,
        },
      },
    ],
  });

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