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

const Player = ({ playerId, players }) => {
  const playerStats = useQuery(
    `player ${playerId}`,
    async () => {
      const { data } = await axios.get(`/api/players/${playerId}`);
      data.sort((a, b) => a.rank - b.rank);
      return data.filter((x) => x.value > 0);
    },
    {
      placeholderData: [],
    }
  );

  const playerName = players.data.find((x) => x.id === playerId)?.name;

  return (
    <>
      <Heading as="h2" 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">
        <Image
          display="inline"
          width="48px"
          height="48px"
          src={`https://minotar.net/avatar/${playerId.replaceAll("-", "")}/48`}
          mr="4"
          rounded="md"
        />
        {playerName}
      </Heading>
      <Table size="sm" variant="striped">
        <Thead>
          <Tr>
            <Th>Statistic</Th>
            <Th isNumeric>Rank</Th>
            <Th isNumeric>Value</Th>
          </Tr>
        </Thead>
        <Tbody>
          {playerStats.data.map((x, i) => {
            return (
              <Tr key={i}>
                <Td>
                  <Link to={`/statistic/${x.type}/${x.name}`}>
                    {prettifyStatisticName(x.type, x.name)}
                  </Link>
                </Td>
                <Td isNumeric>{x.rank}</Td>
                <Td isNumeric>{x.value}</Td>
              </Tr>
            );
          })}
        </Tbody>
      </Table>
    </>
  );
};

export default Player;
