import React, { useMemo } from "react";
import { useQuery } from "react-query";
import axios from "axios";
import {
  Center,
  Heading,
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
} from "@chakra-ui/react";
import { Link } from "react-router-dom";
import prettifyStatisticName from "./PrettifyStatisticName";

const Statistic = ({ type, name, players }) => {
  const ranking = useQuery(`statistic ${type} ${name}`, async () => {
    const { data } = await axios.get(`/api/statistics/${type}/${name}`);
    return data.filter((x) => x.value > 0);
  });

  const playerDict = useMemo(() => {
    return Object.assign({}, ...players.map((x) => ({ [x.id]: x.name })));
  }, [players]);

  return (
    <>
      <Heading as="h1" size="4xl" my="8">
        <Link to="/">
          <Center>📈</Center>
        </Link>
      </Heading>
      <Heading as="h3" size="sm" mt="8" fontWeight="normal">
        Stonks for
      </Heading>
      <Heading as="h1" size="xl" mb="8">
        {prettifyStatisticName(type, name)}
      </Heading>
      <Table size="sm" variant="striped">
        <Thead>
          <Tr>
            <Th>Player</Th>
            <Th isNumeric>Rank</Th>
            <Th isNumeric>Value</Th>
          </Tr>
        </Thead>
        <Tbody>
          {ranking.isSuccess ? (
            ranking.data.map((x, i) => {
              return (
                <Tr key={i}>
                  <Td>
                    <Link to={`/player/${x.playerId}`}>
                      {playerDict[x.playerId]}
                    </Link>
                  </Td>
                  <Td isNumeric>{x.rank}</Td>
                  <Td isNumeric>{x.value}</Td>
                </Tr>
              );
            })
          ) : (
            <></>
          )}
        </Tbody>
      </Table>
    </>
  );
};

export default Statistic;
