'use client';

import Link from 'next/link';
import { useState, useEffect } from 'react';
import {
  Avatar,
  AvatarFallback,
  AvatarImage,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui';
import { useProfile, useAvatar } from '@/lib/hooks'
import { signOut } from '@/lib/actions';
import { User } from 'lucide-react';

const AvatarDropdown = () => {
  const { profile } = useProfile();
  const { avatarUrl, isLoading } = useAvatar(profile);

  const handleSignOut = async () => {
    await signOut();
  };

  if (isLoading) {
    return (
      <Avatar>
        <AvatarFallback className='animate-pulse'>
          <User size={32} />
        </AvatarFallback>
      </Avatar>
    );
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger>
        <Avatar className='cursor-pointer'>
          {avatarUrl ? (
            <AvatarImage src={avatarUrl} />
          ) : (
            <AvatarFallback className="text-2xl">
              {profile?.full_name 
                ? profile.full_name.split(' ').map(n => n[0]).join('').toUpperCase() 
                : <User size={32} />}
            </AvatarFallback>
          )}
        </Avatar>
      </DropdownMenuTrigger>
      <DropdownMenuContent>
        <DropdownMenuLabel>{profile?.full_name}</DropdownMenuLabel>
        <DropdownMenuSeparator />
        <DropdownMenuItem asChild>
          <Link href='/profile' className='w-full justify-center'>
            Edit profile
          </Link>
        </DropdownMenuItem>
        <DropdownMenuSeparator className='h-[2px]' />
        <DropdownMenuItem asChild>
          <button onClick={handleSignOut} className='w-full justify-center'>
            Log out
          </button>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
};
export default AvatarDropdown;
