import { useLoaderData } from "react-router";
import { GamePanel } from "../components/GamePanel";
import type { BasePlayer, MatchInfo, XCXMember } from "../types";
import { Typography } from "antd";
import { useMemo } from "react";
import { useTitle } from "ahooks";

export default function EventPage() {
  const {
    info: game,
    members,
    uidScore,
  } = useLoaderData<{
    uidScore: Map<string, string>,
    info: MatchInfo,
    members: XCXMember[],
  }>();
  const map = useMemo(() => Object.fromEntries(members.map(e => [e.uid, e])), [members]);
  const players = useMemo(() => {
    return game.players
      .map(e => ({
        ...e,
        name: map[e.uid]?.realname ?? e.name,
        number: map[e.uid]?.number ?? NaN,
      }))
      .sort(((a, b) => +a.number - +b.number));
  }, [game, map]);
  const basePlayers = useMemo<BasePlayer[]>(() => {
    return members.map(e => ({
      ...e,
      name: e.realname,
      nowScore: uidScore.get(e.uid),
    } as BasePlayer))
  }, [members]);
  useTitle(game.title, { restoreOnUnmount: true });
  return (
    <div className="app">
      <Typography.Title>{game.title}</Typography.Title>
      <GamePanel members={basePlayers} title={game.title} players={players} />
    </div>
  );
}