import { generateEmbed } from "@/common/embed";
import { NotFound } from "@/components/not-found";
import { Card } from "@/components/ui/card";
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) {
    return generateEmbed({ title: "Unknown Player", description: "Player not found" });
  }

  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) {
  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>
      </div>

      <Card>
        {player == null && <NotFound message="Player not found" />}
        {player != null && (
          <div className="flex gap-2 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}
                alt="The player's skin"
              />
            </div>

            <div className="flex flex-col gap-2">
              <div>
                <h2 className="text-xl">{player.username}</h2>
                <p className="text-gray-300">{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 <img className="h-[64px]" key={key} src={value} alt={`The player's ${key}`} />;
                  })}
                </div>
              </div>
            </div>
          </div>
        )}
      </Card>
    </div>
  );
}
