import React from "react";
import { useQuery } from "react-query";
import axios from "axios";

import { SimpleGrid, Stat, StatLabel, StatNumber } from "@chakra-ui/react";
import prettifyStatisticName from "./PrettifyStatisticName";
import StackedBar from "./StackedBar";

const AggregatesShowcase = () => {
  const aggregates = useQuery(`aggregates`, async () => {
    const { data } = await axios.get(`/api/aggregates`);
    return data;
  });

  const killedAggregates = aggregates.isSuccess
    ? aggregates.data
        .filter((x) => x.type === "minecraft:killed")
        .sort((a, b) => b.value - a.value)
    : [];
  // const killedTotal = killedAggregates.reduce((acc, val) => acc + val.value, 0);

  const killedByAggregates = aggregates.isSuccess
    ? aggregates.data
        .filter((x) => x.type === "minecraft:killed_by")
        .sort((a, b) => b.value - a.value)
    : [];
  // const killedByTotal = killedByAggregates.reduce(
  //   (acc, val) => acc + val.value,
  //   0
  // );

  const travelAggregates = aggregates.isSuccess
    ? aggregates.data
        .filter(
          (x) => x.type === "minecraft:custom" && x.name.endsWith("one_cm")
        )
        .sort((a, b) => b.value - a.value)
    : [];
  // const travelTotal = travelAggregates.reduce((acc, val) => acc + val.value, 0);

  return aggregates.isSuccess ? (
    <>
      <StackedBar heading="Mobs Killed" aggregates={killedAggregates} />

      <StackedBar heading="Causes of Death" aggregates={killedByAggregates} />

      <StackedBar heading="Preferred Travel" aggregates={travelAggregates} />

      <SimpleGrid columns={2} mt={4} spacingY={4} spacingX={8}>
        {aggregates.data
          .filter(
            (x) =>
              x.type !== "minecraft:killed" &&
              x.type !== "minecraft:killed_by" &&
              !x.name.endsWith("one_cm")
          )
          .map((x, i) => {
            var value = x.value;
            if (x.name === "minecraft:play_one_minute") {
              value = Math.floor(x.value / 20 / 60);
            }

            return (
              <Stat key={i}>
                <StatLabel>{prettifyStatisticName(x.type, x.name)}</StatLabel>
                <StatNumber>{`${value
                  .toString()
                  .replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`}</StatNumber>
              </Stat>
            );
          })}
      </SimpleGrid>
    </>
  ) : (
    <></>
  );
};

export default AggregatesShowcase;
