"use client";

import { AccountInfo } from "@/components/account-info";
import { UserDataContext } from "@/components/providers/userdata-provider";
import { Skeleton } from "@/components/ui/skeleton";
import type { IUserData } from "@/interfaces/userdata.interface";
import {
	type Dispatch,
	type SetStateAction,
	useContext,
	useEffect,
	useState,
} from "react";

const localStorage = typeof window !== "undefined" ? window.localStorage : null;

export function AccountDialog() {
	const userContext = useContext(UserDataContext);
	const token = localStorage?.getItem("sub") || "";
	const haveToken = token.length >= 16 || false;
	console.log(haveToken);
	const [isLoaded, setIsLoaded] = useState<boolean>(false);

	if (!userContext) {
		return (
			<div>
				<p>No account</p>
			</div>
		);
	}

	useEffect(() => {
		if (userContext?.userData) {
			setIsLoaded(true);
		}
	}, [userContext?.userData]);

	if (!isLoaded) {
		return <Skeleton className="w-14 h-10 rounded" />;
	}

	return (
		<div>
			<AccountInfo
				userData={userContext?.userData as IUserData}
				setUserData={
					userContext?.setUserData as Dispatch<SetStateAction<IUserData | undefined>>
				}
				isDisconnected={!haveToken}
			/>
		</div>
	);
}
