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';
import useObservable from '../../../hooks/useObservable';
import { gameIdStore, gameJoinedStore, gameStateStore } from '../../../domain/store';
import { PRE_GAME } from '../../../domain/GameState';
import HeaderAndFooter from '../../util/HeaderAndFooter';

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

const ScoreBoard = styled.div`
  display: flex;
  flex-flow: row wrap;
  justify-content: space-evenly;
  align-items: flex-start;
  align-content: space-around;
  max-width: 80%;
  margin-top: 10%;
`

const LowerContainer = styled.div`
  display: flex;
  flex-flow: column nowrap;
  justify-content: space-between;
  align-items: center;
  margin: 1em;
`

const Label = styled.span`
  padding: 0.2em;
  margin-bottom: 0.5em;
`

const StyledButton = styled(Button)`
  margin-top: 0.5em;
`

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

export default () => {
  const gameId = useObservable(gameIdStore);
  const scores = usePlayerScores();
  const onReturnToStart = () => {
    gameJoinedStore.set(false);
    gameStateStore.set(PRE_GAME);
  }

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

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