"use client";

import { useRobuxBalance } from "@/hooks/roblox/useRobuxBalance";
import { RobuxIcon } from "../roblox/RobloxIcons";
import React, { useState } from "react";
import { ShirtIcon } from "lucide-react";
import { StupidHoverThing } from "../util/MiscStuff";
import { OutfitSelector } from "./OutfitQuickChooser";
import { proxyFetch } from "@/lib/utils";
import { loadThumbnails } from "@/lib/thumbnailLoader";
import Link from "next/link";
import { useFriendsHome } from "@/hooks/roblox/useFriends";
import { useBestFriends } from "@/hooks/roblox/useBestFriends";
import { useCurrentAccount } from "@/hooks/roblox/useCurrentAccount";
import { useFriendsPresence } from "@/hooks/roblox/usePresence";

async function updateOutfit(outfit: { id: number }, acc: { id: number }) {
	try {
		const details = (await (
			await proxyFetch(
				`https://avatar.roblox.com/v1/outfits/${outfit.id}/details`
			)
		).json()) as {
			id: number;
			name: string;
			assets: Array<{ id: number; meta?: Record<string, unknown> }>;
			bodyColors: Record<string, string>;
			scale: Record<string, number>;
			playerAvatarType: "R6" | "R15";
		};

		await proxyFetch(
			`https://avatar.roblox.com/v1/avatar/set-body-colors`,
			{
				method: "POST",
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify(details.bodyColors)
			}
		);

		await proxyFetch(`https://avatar.roblox.com/v1/avatar/set-scales`, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify(details.scale)
		});

		// u cant set avatar item scaling/rotation cuz roblox can't make good web apis
		await proxyFetch(
			`https://avatar.roblox.com/v2/avatar/set-wearing-assets`,
			{
				method: "POST",
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify({
					assets: details.assets
						.map((asset) => ({
							id: asset.id,
							meta: asset.meta
						}))
						.filter((asset) => Boolean(asset.id))
				})
			}
		);

		const avatarType =
			details.playerAvatarType === "R15"
				? 3
				: details.playerAvatarType === "R6"
					? 1
					: null;

		if (avatarType !== null) {
			await proxyFetch(
				`https://avatar.roblox.com/v1/avatar/set-player-avatar-type`,
				{
					method: "POST",
					headers: { "Content-Type": "application/json" },
					body: JSON.stringify({
						playerAvatarType: avatarType
					})
				}
			);
		}

		await proxyFetch(
			`https://avatar.roblox.com/v1/avatar/redraw-thumbnail`,
			{
				method: "POST"
			}
		);

		loadThumbnails([
			{
				type: "AvatarHeadShot",
				targetId: acc.id,
				format: "webp",
				size: "720x720"
			}
		]).catch(() => {});
	} catch (err) {
		console.error(err);
	}
}

export const QuickTopUI = React.memo(function () {
	const f = useFriendsHome();
	const bf = useBestFriends();
	useCurrentAccount();

	useFriendsPresence([...(f ? f : []), ...(bf ? bf : [])].map((a) => a.id));

	const robux = useRobuxBalance();
	const [isOutfitSelectorVisible, setIsOutfitSelectorVisible] =
		useState<boolean>(false);
	return (
		<>
			{isOutfitSelectorVisible ? (
				<OutfitSelector
					setVisible={setIsOutfitSelectorVisible}
					updateOutfit={updateOutfit}
				/>
			) : (
				<></>
			)}
			<div className="z-50 fixed top-4 right-4 flex gap-2 items-center text-text">
				<StupidHoverThing text="Change Outfit">
					<button
						className="rounded-full bg-surface0/70 ring-1 ring-surface1/60 flex items-center justify-center h-10 w-10 text-text shadow-sm transition hover:bg-surface1/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue/60"
						onClick={() => {
							setIsOutfitSelectorVisible((a) => !a);
						}}
					>
						<ShirtIcon className="h-5 w-5" />
					</button>
				</StupidHoverThing>

				<StupidHoverThing
					text={
						!robux
							? "You might probably have some Robux..."
							: `You have ${robux.toLocaleString()} Robux`
					}
				>
					<div className="rounded-full bg-surface0/70 ring-1 ring-surface1/60 flex items-center h-10 px-3 gap-2 text-text shadow-sm">
						<RobuxIcon className="w-5 h-5 text-green" />
						<p className="text-sm font-super-mono tabular-nums">
							{robux ? robux.toLocaleString() : "..."}
						</p>
					</div>
				</StupidHoverThing>
			</div>
		</>
	);
});

export const QuickTopUILogoPart = React.memo(function () {
	return (
		<div className="z-15 relative top-4 left-4 flex gap-3 items-center rounded-full">
			<Link
				href="/"
				className="flex h-8 w-8 items-center justify-center rounded-full"
			>
				<img src="/roblox.png" className="w-6 h-6" alt="" />
			</Link>
			<Link
				href="/"
				className="gap-2 flex items-center text-sm font-medium"
			>
				<p>{"Roblox"}</p>
				{/* <p className="text-surface2 line-clamp-1">
					{process.env.NODE_ENV} {process.env.NEXT_PUBLIC_CWD}{" "}
					{process.env.NEXT_PUBLIC_ARGV0}
				</p> */}
			</Link>
		</div>
	);
});
