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 { Player } from "mcutils-library/dist/types/player/player";
import { Metadata } from "next";
import Image from "next/image";

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

export async function generateMetadata({ params: { id } }: Params): Promise<Metadata> {
  const player = await getData(id);
  if (player == null) {
    return generateEmbed({ title: "Unknown Player", description: "Invalid UUID / Username" });
  }

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

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

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

async function getData(id: string): Promise<Player | null> {
  try {
    const cachedPlayer = await getPlayer(id);
    return cachedPlayer.player;
  } catch (error) {
    return null; // Player not found
  }
}

export default async function Page({ params }: Params): Promise<JSX.Element> {
  const player = await getData(params.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>
        {player == null && <NotFound message="Invalid UUID / Username" />}
        {player != null && (
          <div className="flex gap-4 flex-col md:flex-row">
            <div className="flex justify-center md: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">
              <div>
                <h2 className="text-xl">{player.username}</h2>
                <p className="text-primary">{player.uniqueId}</p>
              </div>

              <div className="flex flex-col gap-2">
                <p className="text-lg">Skin Parts</p>
                <div className="flex gap-2">
                  {Object.entries(player.skin.parts).map(([key, value]) => {
                    return (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img className="h-[64px]" key={key} src={value} alt={`The player's ${key}`} loading="lazy" />
                    );
                  })}
                </div>
              </div>
            </div>
          </div>
        )}
      </Card>
    </div>
  );
}
