import DisplayName from "@/components/player/displayname"
import { getGuild } from "@/lib/hypixel/api/guild"
import { getUuid } from "@/lib/hypixel/api/mojang"
import { getPlayer } from "@/lib/hypixel/api/player"
import { getExactLevel } from "@/lib/hypixel/level"
import { Loader2Icon } from "lucide-react"
import { Suspense } from "react"
import Sidebar from "./_components/Sidebar"
import BedwarsStats from "./_stats/bedwars/bedwars"
import SkyWarsStats from "./_stats/skywars/skywars"

export default async function PlayerPage({
    params
}: {
    params: Promise<{ ign: string }>
}) {
    const { ign } = await params

    return (
        <Suspense
            fallback={
                <div className="flex flex-col justify-center items-center h-screen">
                    <Loader2Icon className="animate-spin size-30" />
                    <p>{`Loading stats for ${ign}`}</p>
                </div>
            }
        >
            <SuspendedPage ign={ign} />
        </Suspense>
    )
}

async function SuspendedPage({ ign: pign }: { ign: string }) {
    const uuid = await getUuid(pign)
    if (!uuid) {
        return (
            <div className="flex flex-col items-center min-h-screen">
                <h1 className="mt-25">Player not found</h1>
            </div>
        )
    }

    const player = await getPlayer(uuid)

    if (!player) {
        return (
            <div className="flex flex-col items-center min-h-screen">
                <h1 className="mt-25">Player not found</h1>
            </div>
        )
    }

    const guild = await getGuild(uuid)

    const level = getExactLevel(player.networkExp)

    return (
        <div className="flex flex-col items-center">
            <h1 className="text-3xl font-bold mt-25">
                <DisplayName
                    ign={player.displayname}
                    rank={player.newPackageRank}
                    monthly={player.monthlyPackageRank}
                    rankColor={player.monthlyRankColor}
                    plusColor={player.rankPlusColor}
                    guildTag={guild?.tag}
                    tagColor={guild?.tagColor}
                />
            </h1>
            <h1>
                {player.uuid}
            </h1>
            <div className="flex gap-6 px-6 mt-8 w-full max-w-7xl">
                <Sidebar level={level} ign={pign} player={player} guild={guild ?? undefined} />
                <div className="space-y-4 w-3/4">
                    <BedwarsStats stats={player.stats.Bedwars} />
                    <SkyWarsStats stats={player.stats.SkyWars} />
                </div>
            </div>
        </div>
    )
}
