"use client";

import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { notFound } from "next/navigation";
import { Separator } from "@/components/ui/separator";
import { getUserByUserId, UserProfileDetails } from "@/lib/profile";
import { UserProfileHeader } from "@/components/roblox/UserProfileHeader";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { ShieldBanIcon } from "lucide-react";
import Link from "next/link";
import { useFriendsHome } from "@/hooks/roblox/useFriends";
import { FriendCarousel } from "@/components/roblox/FriendCarousel";

interface UserProfileContentProps {
	userId: string;
}

function ProfileMoreDetails({ profile }: { profile: UserProfileDetails }) {
	const theirFriends = useFriendsHome(profile.id.toString());

	return (
		<>
			{!theirFriends && <Skeleton className="w-full h-64" />}
			<FriendCarousel
				title="Friends"
				className="overflow-visible"
				friends={theirFriends || []}
			/>
		</>
	);
}

export default function UserProfileContent({
	userId
}: UserProfileContentProps) {
	const { data: profile, isLoading } = useQuery({
		queryKey: ["user-profile", userId],
		queryFn: () => getUserByUserId(userId),
		enabled: !!userId
	});

	// Set dynamic document title
	useEffect(() => {
		if (profile?.displayName) {
			document.title = `${profile.displayName}'s profile | Roblox`;
		}
	}, [profile]);

	if (isLoading)
		return (
			<div className="page-container py-6 space-y-6">
				<div className="h-10 w-64 rounded-lg bg-surface0/60 animate-pulse" />
				<div className="panel-soft h-32 animate-pulse" />
				<div className="panel-soft h-64 animate-pulse" />
			</div>
		);
	if (!profile) notFound();

	return (
		<div className="page-container py-6 space-y-6">
			<UserProfileHeader user={profile} />
			<Separator className="bg-surface0/60" />
			<div className="panel-soft p-6">
				<h2 className="text-lg font-semibold text-text">About</h2>
				<p className="mt-2 text-sm text-subtext1 break-all whitespace-pre-line">
					{profile.description || "No description provided yet."}
				</p>
			</div>
			{profile.isBanned && (
				<>
					<div className="justify-center w-full pt-6">
						<Alert
							variant="default"
							className="bg-base/50 space-x-2"
						>
							<ShieldBanIcon />
							<AlertTitle>This user is banned</AlertTitle>
							<AlertDescription>
								Their Roblox account appears to be terminated
								from the platform. You can see their inventory
								and RAP history on{" "}
								<Link
									className="text-blue decoration-blue underline"
									href={`https://www.rolimons.com/player/${profile.id}`}
								>
									Rolimons
								</Link>
							</AlertDescription>
						</Alert>
					</div>
				</>
			)}
			{!profile.isBanned && <ProfileMoreDetails profile={profile} />}
		</div>
	);
}
