import DisplayName from "@/components/player/displayname"
import { Card, CardContent } from "@/components/ui/card"
import { COOKIE_VALUES } from "@/data/general"
import { env } from "@/lib/env/server"
import { getGuild } from "@/lib/hypixel/api/guild"
import { getUuid } from "@/lib/hypixel/api/mojang"
import { getSession } from "@/lib/hypixel/api/online"
import { getPlayer } from "@/lib/hypixel/api/player"
import { getExactLevel } from "@/lib/hypixel/general/level"
import { Loader2Icon, ShieldAlert } from "lucide-react"
import { Metadata } from "next"
import { cookies } from "next/headers"
import { Suspense } from "react"
import z from "zod"
import PlayerStats, { PlayerPageLoadText } from "./_client"
import Sidebar from "./_components/Sidebar"

export async function generateMetadata({ params }: { params: Promise<{ ign: string }> }): Promise<Metadata> {
    const { ign } = await params
    const user = await getUuid(ign)
    return { title: user !== null ? user.name : "Player not found" }
}

export default function PlayerPage({ params }: PageProps<"/player/[ign]">) {
    const maintenance = env.MAINTENANCE_MODE

    if (maintenance) {
        return (
            <div className="flex flex-col gap-2 justify-center items-center h-screen">
                <ShieldAlert className="size-30" />
                <h1 className="text-xl">Not available right now. This is just so I could have a front page for Hypixel Production API Key.</h1>
            </div>
        )
    }

    return (
        <Suspense
            fallback={
                <div className="flex flex-col justify-center items-center h-screen">
                    <Loader2Icon className="animate-spin size-30" />
                    <PlayerPageLoadText />
                </div>
            }
        >
            <SuspendedPage params={params} />
        </Suspense>
    )
}

async function SuspendedPage({ params }: Pick<PageProps<"/player/[ign]">, "params">) {
    const { ign: pign } = await params
    const c = await cookies()

    const mc = await getUuid(pign)
    if (!mc) {
        return (
            <div className="flex flex-col items-center min-h-screen">
                <h1 className="mt-35">Player not found</h1>
            </div>
        )
    }

    const player = await getPlayer(mc.id)

    if (!player) {
        return (
            <div className="flex flex-col items-center min-h-screen">
                <h1 className="mt-35">Player hasn&apos;t joined hypixel</h1>
            </div>
        )
    }

    const session = await getSession(mc.id)
    const guild = await getGuild(mc.id)
    const level = getExactLevel(player.networkExp)

    const schema = z.array(z.string())
    const { data: layout } = schema.safeParse(JSON.parse(c.get(COOKIE_VALUES.statsOrder)?.value ?? "null"))

    return (
        <div className="flex flex-col items-center pb-5">
            <DisplayName
                ign={player.displayname}
                uuid={player.uuid}
                rank={player.newPackageRank}
                monthly={player.monthlyPackageRank}
                rankColor={player.monthlyRankColor}
                plusColor={player.rankPlusColor}
                guildTag={guild?.tag}
                tagColor={guild?.tagColor}
                specialRank={player.rank}
                lastLogin={player.lastLogin}
                lastLogout={player.lastLogout}
                prefix={player.prefix}
            />
            <h1>
                {player.uuid}
            </h1>
            <div className="flex flex-col gap-6 px-6 pb-4 mt-8 w-full max-w-7xl md:flex-row">
                <Sidebar
                    level={level}
                    ign={pign}
                    player={player}
                    guild={guild ?? undefined}
                    rank={player.newPackageRank}
                    specialRank={player.rank}
                    eulaCoins={player.eulaCoins}
                    session={session}
                />
                {player.stats !== undefined ?
                    <PlayerStats stats={player.stats} achievements={player.achievements} layout={layout} /> :
                    (
                        <div className="w-3/4">
                            <Card>
                                <CardContent className="flex justify-center">
                                    <h1 className="text-xl font-bold">
                                        No stats avaiable. If they are staff then they most likely have their api off.
                                    </h1>
                                </CardContent>
                            </Card>
                        </div>
                    )}
            </div>
        </div>
    )
}
