"use client";

import { useRouter } from "next/navigation";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { ChevronDown } from "lucide-react";
import { logout } from "@/lib/api";

interface UserNavProps {
  username: string;
  role: string;
}

export function UserNav({ username, role }: UserNavProps) {
  const router = useRouter();

  const ADMIN_ROLES = ["auditor", "domain_auditor", "admin", "domain_admin", "superadmin"];

  const ROLE_LABELS: Record<string, string> = {
    user: "Benutzer",
    auditor: "Auditor",
    domain_auditor: "Domain-Auditor",
    admin: "Admin",
    domain_admin: "Domain-Admin",
    superadmin: "Superadmin",
  };

  async function handleLogout() {
    try {
      await logout();
    } catch {
      // ignore logout errors
    }
    router.push(ADMIN_ROLES.includes(role) ? "/admin/login" : "/");
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="ghost"
          size="sm"
          className="flex items-center gap-2"
          aria-label="Benutzermenu"
        >
          <span className="text-sm font-medium">{username}</span>
          {username !== role && (
            <Badge variant="secondary" className="text-xs">
              {ROLE_LABELS[role] ?? role}
            </Badge>
          )}
          <ChevronDown className="h-4 w-4 opacity-50" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-48">
        <DropdownMenuItem onClick={() => router.push("/settings")}>
          Profil &amp; Einstellungen
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem onClick={handleLogout} className="text-red-600">
          Abmelden
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
