'use client';
import Link from 'next/link';
import {
  BasedAvatar,
  Button,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui';
import { useAuth } from '@/lib/hooks/context';
import { useRouter } from 'next/navigation';
import { signOut } from '@/lib/queries';
import { useSupabaseClient } from '@/utils/supabase';

export const AvatarDropdown = () => {
  const { profile, avatar, refreshUser } = useAuth();
  const router = useRouter();
  const client = useSupabaseClient();

  const handleSignOut = async () => {
    try {
      if (!client) throw new Error('Supabase client not found!');
      const { error } = await signOut(client);
      if (error) throw new Error(error.message);
      await refreshUser();
      router.push('/');
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger>
        <BasedAvatar
          src={avatar}
          fullName={profile?.full_name}
          className='lg:h-12 lg:w-12 my-auto'
          fallbackProps={{ className: 'text-xl font-semibold' }}
          userIconProps={{ size: 32 }}
        />
      </DropdownMenuTrigger>
      <DropdownMenuContent>
        {(profile?.full_name ?? profile?.email) && (
          <>
            <DropdownMenuLabel className='font-bold'>
              {profile.full_name?.trim() ?? profile.email?.trim()}
            </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'
            variant='ghost'
          >
            Sign Out
          </Button>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
};
