import React from 'react';
import styled from "styled-components";
import Loading from '../../util/Loading';
import Button from "../../util/Button";
import PlayerScoreTile from "./PlayerScoreTile";
import usePlayerScores from '../../../hooks/usePlayerScores';
import ClickToCopy from '../../util/ClickToCopy';

const Container = styled.div`
  display: flex;
  flex-flow: column nowrap;
  justify-content: space-around;
  align-items: center;
`

const ScoreBoard = styled.div`
  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;
  align-items: center;
  align-content: space-around;
`

const Label = styled.span`
  padding: 0.2em;
`

const getUrl = gameId => {
  const u = new URL(window.location.href);
  u.searchParams.append("summary", gameId);
  return u.href;
}

export default ({ gameId, onReturnToStart }) => {
  const scores = usePlayerScores(gameId);

  if (!scores) {
    return <Loading/>
  }

  return (
    <Container>
      <ScoreBoard>
        {
          scores
            .filter(({ currentRound }) => currentRound === null)
            .sort((p1, p2) => p1.totalScore > p2.totalScore ? -1 : (p1.totalScore < p2.totalScore ? 1 : 0))
            .map(({ name, guesses, totalScore }) => <PlayerScoreTile key={name} {...{ name, guesses, totalScore }} />)
        }
      </ScoreBoard>
      <Label>This page can be directly linked with:</Label>
      <Label><ClickToCopy text={getUrl(gameId)} /></Label>
      <Button onClick={onReturnToStart}>Return to Start</Button>
    </Container>
  );
}
