import LoginIcon from './icons/login-icon';
import { UserModel } from '@/lib/feature/user/user.model';
import EmptyProfileIcon from '@/ui/components/internal/user-profile/icons/empty-profile-icon';
import { UserManagmentPopover } from '@/ui/components/internal/user-profile/popover/user-manage';
import {
    Avatar,
    AvatarFallback,
    AvatarImage,
} from '@/ui/components/shadcn/avatar';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/ui/components/shadcn/popover';
import { SignInButton } from '@clerk/nextjs';

const genInitials = (name: string | null) => {
    if (!name) {
        return 'US';
    }

    return name.match(/(\b\S)?/g)?.join('') || '';
};

export const UserButton = ({ user }: { user: UserModel }) => {
    const userName = user.name || 'PlaceHolder';
    return (
        <Popover>
            <PopoverTrigger>
                <Avatar className='flex h-[47px] w-[47px] items-center justify-center align-middle'>
                    <>
                        <AvatarImage
                            src={user.imageUrl || 'https://no-image'}
                            className='fill-white'
                        />
                        <AvatarFallback>{genInitials(userName)}</AvatarFallback>
                    </>
                </Avatar>
            </PopoverTrigger>
            <PopoverContent align='end' className='w-[200px]'>
                <UserManagmentPopover username={userName} />
            </PopoverContent>
        </Popover>
    );
};

export const BlankUserButton = () => {
    return (
        <>
            <SignInButton>
                <Avatar className='group flex h-[47px] w-[47px] items-center justify-center align-middle cursor-pointer'>
                    <>
                        <AvatarImage />
                        <AvatarFallback>
                            <EmptyProfileIcon className='block group-hover:hidden h-[22px] w-[22px] fill-black dark:fill-white font-light' />
                            <LoginIcon className='hidden group-hover:block h-[22px] w-[22px] fill-black dark:fill-white font-light' />
                        </AvatarFallback>
                    </>
                </Avatar>
            </SignInButton>
        </>
    );
};
