/* eslint-disable @next/next/no-img-element */
import { CopyButton } from "@/app/components/copy-button";
import { ErrorCard } from "@/app/components/error-card";
import { LookupPlayer } from "@/app/components/player/lookup-player";
import { PlayerView } from "@/app/components/player/player-view";
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "@/app/components/ui/context-menu";
import { Colors } from "@/app/common/colors";
import { generateEmbed } from "@/app/common/embed";
import { isValidPlayer } from "@/app/common/player";
import config from "@root/config.json";
import { CachedPlayer, getPlayer, McUtilsAPIError } from "mcutils-library";
import { Metadata, Viewport } from "next";
import { ReactElement } from "react";
import { Title } from "@/app/components/title";

/**
 * Force the page to be dynamic, so it will be regenerated on every request
 */
export const revalidate = 0;

type Params = {
  params: {
    id: string;
  };
};

export async function generateViewport({ params: { id } }: Params): Promise<Viewport> {
  const validPlayer = await isValidPlayer(id);
  return {
    themeColor: validPlayer ? Colors.green : Colors.red,
  };
}

export async function generateMetadata({ params: { id } }: Params): Promise<Metadata> {
  // No id provided
  if (!id || id.length === 0) {
    return generateEmbed({
      title: "Player Lookup",
      description: "Click to lookup a player.",
    });
  }

  try {
    const { username, uniqueId, skin } = await getPlayer(id);
    const headPartUrl = skin.parts.head;

    return generateEmbed({
      title: `${username}'s Profile`,
      description: `UUID: ${uniqueId}\n\nClick to view more information about the player.`,
      image: headPartUrl,
    });
  } catch (err) {
    // An error occurred
    return generateEmbed({
      title: "Player Not Found",
      description: (err as McUtilsAPIError).message,
    });
  }
}

export default async function Page({ params: { id } }: Params): Promise<ReactElement> {
  let error: string | undefined = undefined; // The error to display
  let player: CachedPlayer | undefined = undefined; // The player to display

  // Try and get the player to display
  try {
    player = id ? await getPlayer(id) : undefined;
  } catch (err) {
    error = (err as McUtilsAPIError).message; // Set the error message
  }

  return (
    <div className="h-full flex flex-col items-center">
      <div className="mb-4 text-center">
        <Title
          title="Player Lookup"
          subtitle="You can enter a players uuid or username to get information about the player."
        />

        <LookupPlayer currentPlayer={id && id[0]} />
      </div>

      {error && <ErrorCard message={error} />}
      {player != undefined && (
        <ContextMenu>
          <ContextMenuTrigger>
            <PlayerView player={player} />
          </ContextMenuTrigger>
          <ContextMenuContent className="flex flex-col">
            <CopyButton content={player.username}>
              <ContextMenuItem>Copy Player Username</ContextMenuItem>
            </CopyButton>

            <CopyButton content={player.uniqueId}>
              <ContextMenuItem>Copy Player UUID</ContextMenuItem>
            </CopyButton>

            <CopyButton content={`${config.publicUrl}/player/${id}`}>
              <ContextMenuItem>Copy Share URL</ContextMenuItem>
            </CopyButton>
          </ContextMenuContent>
        </ContextMenu>
      )}
    </div>
  );
}
