'use client'

import { useCurrentUser } from '@/hooks/useCurrentUser'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { IoExitOutline } from 'react-icons/io5'
import LogoutButton from '@/components/auth/logout-button'

const fallbackInitials = (name?: string | null | undefined): string => {
  return (name ?? '').split(' ').map((w: string) => w[0]).join('').toUpperCase()
}

const UserButton = () => {
  const user = useCurrentUser()

  return (
    <DropdownMenu>
      <DropdownMenuTrigger className="outline-0">
        <Avatar>
          <AvatarImage src={user?.image || ''} alt="User Avatar"/>
          <AvatarFallback className="bg-sky-600 text-muted text-lg font-light">
            {fallbackInitials(user?.name)}
          </AvatarFallback>
        </Avatar>
      </DropdownMenuTrigger>
      <DropdownMenuContent className="w-28 p-0" align="end">
        <LogoutButton>
          <DropdownMenuItem className="cursor-pointer p-2">
            <IoExitOutline className="w-4 h-4 mr-2"/>
            Logout
          </DropdownMenuItem>
        </LogoutButton>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}

export default UserButton
