/* eslint-disable @next/next/no-img-element */
import { Card } from "@/app/components/card";
import { NotFound } from "@/app/components/not-found";
import { LookupPlayer } from "@/app/components/player/lookup-player";
import { generateEmbed } from "@/common/embed";
import { getPlayer } from "mcutils-library";
import { CachedPlayer } from "mcutils-library/dist/types/cache/cachedPlayer";
import { McUtilsAPIError } from "mcutils-library/dist/types/error";
import { Player, SkinPart } from "mcutils-library/dist/types/player/player";
import { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";

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

export async function generateMetadata({ params: { id } }: Params): Promise<Metadata> {
  const { error, player } = await fetchPlayer(id);

  if (error && player == undefined) {
    return generateEmbed({ title: "Unknown Player", description: error });
  }

  const { username, uniqueId, skin } = player as Player;
  const headPartUrl = skin.parts.head;

  const description = `
    Username: ${username}
    UUID: ${uniqueId}`;

  return generateEmbed({
    title: `${username}`,
    description: description,
    image: headPartUrl,
  });
}

/**
 * Gets the player's data from the uuid or username
 *
 * @param id the player's uuid or username
 * @returns the player's data or an error message
 */
async function getData(id: string): Promise<CachedPlayer | null> {
  return await getPlayer(id);
}

/**
 * Fetches the player's data from the uuid or username
 *
 * @param id the player's uuid or username
 * @returns the player's data or an error message
 */
async function fetchPlayer(id: string): Promise<{ error: string | undefined; player: Player | undefined }> {
  let error: string | undefined = undefined;
  let player: Player | undefined = undefined;

  try {
    player = (await getData(id))?.player;
  } catch (err) {
    error = (err as McUtilsAPIError).message;
  }

  return { error, player };
}

export default async function Page({ params: { id } }: Params): Promise<JSX.Element> {
  const { error, player } = await fetchPlayer(id);

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

        <LookupPlayer />
      </div>

      <Card className="w-max xs:w-fit">
        {error && <NotFound message={error} />}
        {player != null && (
          <div className="flex gap-4 flex-col xs:flex-row">
            <div className="flex justify-center xs:justify-start">
              <Image
                className="w-[96px] h-[96px]"
                src={player.skin.parts.head}
                width={96}
                height={96}
                quality={100}
                alt="The player's skin"
              />
            </div>

            <div className="flex flex-col gap-2 divide-y divide-neutral-200 dark:divide-neutral-700">
              <div>
                <h2 className="text-xl text-primary">{player.username}</h2>
                <p>{player.uniqueId}</p>
              </div>

              <div className="flex flex-col gap-2">
                <p className="text-lg mt-2">Skin Parts</p>
                <div className="flex gap-2">
                  {Object.entries(player.skin.parts)
                    .filter(([part]) => part !== SkinPart.HEAD) // Don't show the head part again
                    .map(([part, url]) => {
                      return (
                        <Link key={part} href={url} target="_blank">
                          <img className="h-[64px]" src={url} alt={`The player's ${part}`} loading="lazy" />
                        </Link>
                      );
                    })}
                </div>
              </div>
            </div>
          </div>
        )}
      </Card>
    </div>
  );
}
