'use client';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  BasedAvatar,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui';
import { useConvexAuth, useQuery } from 'convex/react';
import { useTVMode } from '@/components/providers';
import { useAuthActions } from '@convex-dev/auth/react';
import { api } from '~/convex/_generated/api';

export const AvatarDropdown = () => {
  const router = useRouter();
  const { isLoading, isAuthenticated } = useConvexAuth();
  const { signOut } = useAuthActions();
  const { tvMode, toggleTVMode } = useTVMode();
  const user = useQuery(api.auth.getUser);
  const currentImageUrl = useQuery(
    api.files.getImageUrl,
    user?.image ? { storageId: user.image } : 'skip',
  );

  if (isLoading)
    return <BasedAvatar className='animate-pulse lg:h-10 lg:w-10' />;
  if (!isAuthenticated) return <div />;

  return (
    <DropdownMenu>
      <DropdownMenuTrigger>
        <BasedAvatar
          src={currentImageUrl}
          fullName={user?.name}
          className='lg:h-10 lg:w-10'
          fallbackProps={{ className: 'text-xl font-semibold' }}
          userIconProps={{ size: 32 }}
        />
      </DropdownMenuTrigger>
      <DropdownMenuContent>
        {(user?.name ?? user?.email) && (
          <>
            <DropdownMenuLabel className='font-bold text-center'>
              {user.name?.trim() ?? user.email?.trim()}
            </DropdownMenuLabel>
            <DropdownMenuSeparator />
          </>
        )}
        <DropdownMenuItem asChild>
          <button
            onClick={toggleTVMode}
            className='w-full justify-center cursor-pointer'
          >
            {tvMode ? 'Normal Mode' : 'TV Mode'}
          </button>
        </DropdownMenuItem>
        <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={() =>
              void signOut().then(() => {
                router.push('/signin');
              })
            }
            className='w-full justify-center cursor-pointer'
          >
            Sign Out
          </button>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
};
