'use client';

import Link from 'next/link';
import {
	Avatar,
	AvatarFallback,
	AvatarImage,
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuItem,
	DropdownMenuLabel,
	DropdownMenuSeparator,
	DropdownMenuTrigger,
} from '@/components/ui';
import { useAuth } from '@/components/context';
import { useRouter } from 'next/navigation';
import { signOut } from '@/lib/actions';
import { User } from 'lucide-react';

const AvatarDropdown = () => {
	const { profile, avatarUrl, isLoading, refreshUserData } = useAuth();
	const router = useRouter();

	const handleSignOut = async () => {
		const result = await signOut();
		if (result?.success) {
			await refreshUserData();
			router.push('/sign-in');
		}
	};

	const getInitials = (name: string | null | undefined): string => {
		if (!name) return '';
		return name
			.split(' ')
			.map((n) => n[0])
			.join('')
			.toUpperCase();
	};

	return (
		<DropdownMenu>
			<DropdownMenuTrigger>
				<Avatar className='cursor-pointer'>
					{avatarUrl ? (
						<AvatarImage
							src={avatarUrl}
							alt={getInitials(profile?.full_name)}
							width={64}
							height={64}
						/>
					) : (
						<AvatarFallback className='text-sm'>
							{profile?.full_name ? (
								getInitials(profile.full_name)
							) : (
								<User size={32} />
							)}
						</AvatarFallback>
					)}
				</Avatar>
			</DropdownMenuTrigger>
			<DropdownMenuContent>
				<DropdownMenuLabel>{profile?.full_name}</DropdownMenuLabel>
				<DropdownMenuSeparator />
				<DropdownMenuItem asChild>
					<Link
						href='/profile'
						className='w-full justify-center cursor-pointer'
					>
						Edit profile
					</Link>
				</DropdownMenuItem>
				<DropdownMenuSeparator className='h-[2px]' />
				<DropdownMenuItem asChild>
					<button
						onClick={handleSignOut}
						className='w-full justify-center cursor-pointer'
					>
						Sign Out
					</button>
				</DropdownMenuItem>
			</DropdownMenuContent>
		</DropdownMenu>
	);
};
export default AvatarDropdown;
