import { CircleUser } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";

import { useLogout, useMe } from "../api/queries";
import { Button } from "@/components/ui/button";
import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from "@/components/ui/menu";

export function UserMenu() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { data: me } = useMe();
  const logout = useLogout();

  const onSignOut = () =>
    logout.mutate(undefined, {
      onSuccess: () => navigate("/login", { replace: true }),
    });

  if (!me) return null;

  return (
    <Menu>
      <MenuTrigger
        render={
          <Button variant="ghost" size="sm" className="max-w-44">
            <CircleUser className="size-4" aria-hidden />
            <span className="truncate">{me.email}</span>
          </Button>
        }
      />
      <MenuContent>
        <div className="px-2 py-1.5">
          <div className="truncate text-sm font-medium">{me.email}</div>
          <div className="text-xs text-muted-foreground">{me.role}</div>
        </div>
        <MenuSeparator />
        <MenuItem closeOnClick={false} disabled={logout.isPending} onClick={onSignOut}>
          {logout.isPending ? t("auth.signingOut") : t("auth.signOut")}
        </MenuItem>
      </MenuContent>
    </Menu>
  );
}
