import useComponentSize from "@rehooks/component-size";
import { Spin } from "antd";
import React, { FC, useRef } from "react";
// We expect a TypeScript error here because we have not downloaded the plotly types package.
//@ts-expect-error
import Plot from "react-plotly.js";

import {
  CellSet,
  WidgetPluginProps,
  useQueryResult,
} from "@activeviam/activeui-sdk";

const getCountriesAndValues = (data?: CellSet): [string[], number[]] => {
  if (!data) {
    return [[], []];
  }

  const [columnsAxis, rowsAxis] = data.axes;
  const numberOfYears = columnsAxis.positions.length;
  const numberOfCountries = rowsAxis.positions.length;

  const valuesForSelectedYear = new Array(numberOfCountries).fill(null);
  data.cells.forEach((cell) => {
    const rowIndex = Math.floor(cell.ordinal / numberOfYears);
    const columnIndex = cell.ordinal % numberOfYears;
    const year = columnsAxis.positions[columnIndex][0].captionPath[0];
    // Only display the 2019 values for now.
    if (year === "2019") {
      valuesForSelectedYear[rowIndex] = cell.value;
    }
  });

  return [
    rowsAxis.positions.map((position) => position[0].captionPath[2]),
    valuesForSelectedYear,
  ];
};

export const Map: FC<WidgetPluginProps> = (props) => {
  const container = useRef<HTMLDivElement>(null);
  const { height, width } = useComponentSize(container);

  const { data, error, isLoading } = useQueryResult({
    serverKey: "my-server",
    queryId: props.queryId,
    query: {
      mdx: `SELECT
              Crossjoin(
                [Green-growth].[Year].[Year].Members,
                [Measures].[Real GDP per capita (USD).MEAN]
              ) ON COLUMNS,
              [Countries].[Country].[Country_Name].Members ON ROWS
              FROM [Green-growth]`,
    },
  });

  // countries and values only depend on `data`.
  const [countries, values] = getCountriesAndValues(data);

  return (
    <div
      ref={container}
      style={{
        ...props.style,
        height: "100%",
      }}
    >
      {error ? (
        <div>{error.stackTrace}</div>
      ) : isLoading || !data ? (
        <Spin />
      ) : (
        <Plot
          data={[
            {
              type: "choropleth",
              locationmode: "country names",
              locations: countries,
              z: values,
              text: countries,
              autocolorscale: true,
            },
          ]}
          layout={{
            height,
            width,
            margin: {
              l: 20,
              t: 30,
              r: 20,
              b: 20,
            },
          }}
        />
      )}
    </div>
  );
};
