import { useAuth } from "@/contexts/AuthContext";
import { cn } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { LogOut, User } from "lucide-react";
import { useNavigate } from "react-router-dom";

interface Props {
  collapsed?: boolean;
}

const UserMenu = (props: Props) => {
  const { collapsed } = props;
  const { currentUser, logout } = useAuth();
  const navigate = useNavigate();

  if (!currentUser) return null;

  const handleLogout = async () => {
    await logout();
    navigate("/auth");
  };

  return (
    <div className={cn("w-auto flex flex-row justify-start items-center", collapsed ? "px-1" : "px-3")}>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <div className="flex items-center gap-2 cursor-pointer p-1 rounded-md hover:bg-black/5 dark:hover:bg-white/5 transition">
            <div className="w-8 h-8 rounded-full overflow-hidden bg-primary/10 flex items-center justify-center shrink-0">
               {currentUser.avatarUrl ? (
                 <img src={currentUser.avatarUrl} alt="Avatar" className="w-full h-full object-cover" />
               ) : (
                 <span className="text-sm font-semibold text-primary">
                    {currentUser.nickname?.[0] || currentUser.username[0].toUpperCase()}
                 </span>
               )}
            </div>
            {!collapsed && (
              <span className="text-sm font-medium truncate max-w-[120px]">
                {currentUser.nickname || currentUser.username}
              </span>
            )}
          </div>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="start" className="w-56">
          <DropdownMenuLabel>{currentUser.username}</DropdownMenuLabel>
            {currentUser.email && (
              <p className="text-xs text-muted-foreground px-2 pb-2 truncate">{currentUser.email}</p>
            )}
          <DropdownMenuSeparator />
          <DropdownMenuItem onClick={() => navigate("/setting")}>
            <User className="mr-2 h-4 w-4" />
            <span>Profile settings</span>
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem onClick={handleLogout} className="text-red-500 focus:text-red-500 focus:bg-red-500/10">
            <LogOut className="mr-2 h-4 w-4" />
            <span>Log out</span>
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  );
};

export default UserMenu;
