import { GetStaticPaths, GetStaticProps } from "next";
import React from "react";

import { DefaultLayout } from "@/components/DefaultLayout";
import { Link } from "@/components/Link";
import { Title } from "@/components/Title";

import { CrashTheServer } from "../../components/games/crash-the-server/CrashTheServer";
import { FlappyCodey } from "../../components/games/FlappyCodey";
import { GooseRun } from "../../components/games/Gooserun";
import { Game, games } from "../../content/games";

import styles from "./[slug].module.css";

interface Props {
  game: Game;
}

const gameComponents = {
  "flappy-codey": FlappyCodey,
  "crash-the-server": CrashTheServer,
  "goose-run-game": GooseRun,
};

type GameSlug = keyof typeof gameComponents;

export default function GamePage({ game }: Props) {
  const GameComponent = gameComponents[game.slug as GameSlug];
  const pageClass =
    game.slug === "crash-the-server"
      ? `${styles.page} ${styles.crashTheServerTheme}`
      : styles.page;

  const content = (
    <div className={pageClass}>
      <Title>{game.title}</Title>
      <Link href="/game-channel">Back to Game Channel</Link>
      <header className={styles.header}>
        {game.slug === "crash-the-server" && (
          <div className={styles.headerEmoji} aria-hidden="true">
            🖥️💥
          </div>
        )}
        <h1>{game.title}</h1>
        <p>{game.description}</p>
      </header>
      {GameComponent == null ? (
        <p>This game is not implemented yet.</p>
      ) : (
        <GameComponent />
      )}
    </div>
  );

  if (game.slug !== "crash-the-server") {
    return <DefaultLayout>{content}</DefaultLayout>;
  }

  return content;
}

GamePage.Layout = function Layout({ children }: { children: React.ReactNode }) {
  return <>{children}</>;
};

export const getStaticPaths: GetStaticPaths = () => {
  return {
    paths: games
      .filter((game) => game.status === "playable")
      .map((game) => ({ params: { slug: game.slug } })),
    fallback: false,
  };
};

export const getStaticProps: GetStaticProps<Props> = ({ params }) => {
  const slug = params?.slug;
  const game =
    typeof slug === "string"
      ? games.find((candidate) => candidate.slug === slug)
      : undefined;

  if (game == null || game.status !== "playable") {
    return {
      notFound: true,
    };
  }

  return {
    props: {
      game,
    },
  };
};
