'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { isRemoteImageUrl } from '@/lib/avatar';
import { useAuthActions } from '@convex-dev/auth/react';
import { useConvexAuth, useQuery } from 'convex/react';

import { api } from '@spoon/backend/convex/_generated/api.js';
import {
  BasedAvatar,
  Button,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@spoon/ui';

export const AvatarDropdown = () => {
  const router = useRouter();
  const { isLoading, isAuthenticated } = useConvexAuth();
  const { signOut } = useAuthActions();
  const user = useQuery(api.auth.getUser, {});
  const remoteImageUrl = isRemoteImageUrl(user?.image) ? user?.image : null;
  const currentImageUrl = useQuery(
    api.files.getImageUrl,
    user?.image && !remoteImageUrl ? { storageId: user.image } : 'skip',
  );
  const avatarUrl = remoteImageUrl ?? currentImageUrl;

  if (isLoading) {
    return (
      <div className='flex items-center gap-2'>
        <div className='bg-muted h-8 w-16 animate-pulse rounded-md' />
        <div className='bg-muted h-9 w-9 animate-pulse rounded-full' />
      </div>
    );
  }

  if (!isAuthenticated) {
    return (
      <div className='flex items-center gap-2'>
        <Button size='sm' asChild>
          <Link href='/sign-in'>Sign In</Link>
        </Button>
      </div>
    );
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger>
        <BasedAvatar
          src={avatarUrl}
          fullName={user?.name}
          className='h-9 w-9'
          fallbackProps={{ className: 'text-sm font-semibold' }}
          userIconProps={{ size: 20 }}
        />
      </DropdownMenuTrigger>
      <DropdownMenuContent align='end'>
        {(user?.name ?? user?.email) && (
          <>
            <DropdownMenuLabel className='text-center font-bold'>
              {user.name?.trim() ?? user.email?.trim()}
            </DropdownMenuLabel>
            <DropdownMenuSeparator />
          </>
        )}
        <DropdownMenuItem asChild>
          <Link href='/profile' className='w-full cursor-pointer'>
            Edit Profile
          </Link>
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem asChild>
          <button
            onClick={() =>
              void signOut().then(() => {
                router.push('/');
              })
            }
            className='w-full cursor-pointer'
          >
            Sign Out
          </button>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
};
