"use client"
import { signOut } from "next-auth/react";
import { 
  DropdownMenu, 
  DropdownMenuContent, 
  DropdownMenuItem, 
  DropdownMenuSeparator, 
  DropdownMenuTrigger 
} from "@/components/ui/dropdown-menu";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { LogOut } from "lucide-react";
import { User } from "next-auth";

interface UserMenuProps {
  user: User;
}

const getInitials = (user: User) => {
  if (!user.name) return "U";
  const names = user.name.split(" ");
  return names.length > 1
    ? names[0][0] + names[1][0]
    : names[0][0];
};
const UserMenu = ({ user }: UserMenuProps) => {
  const handleLogout = async () => {
    await signOut({ callbackUrl: "/" });
  };
  return (
    <DropdownMenu>
      <DropdownMenuTrigger className="focus:outline-none flex cursor-pointer  gap-3">
        <Avatar className="h-8 w-8 cursor-pointer">
          <AvatarImage src={user.image || ""} alt={user.name || "User"} />
          <AvatarFallback>{getInitials(user)}</AvatarFallback>
        </Avatar>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-56">
        <div className="flex items-center justify-start gap-2 p-2">
          <div className="flex flex-col space-y-1 leading-none">
            {user.name && <p className="font-medium">{user.name}</p>}
            {user.email && (
              <p className="w-[200px] truncate text-sm text-gray-500">
                {user.email}
              </p>
            )}
          </div>
        </div>
        <DropdownMenuSeparator />
        <DropdownMenuItem asChild>
        </DropdownMenuItem>
        <DropdownMenuItem onClick={handleLogout} className="cursor-pointer">
          <LogOut className="mr-2 h-4 w-4" />
          <span>Log out</span>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
};

export default UserMenu;