"use client";

import React from "react";
import Link from "next/link";
import { KeyRound, LogOut, Settings, User } from "lucide-react";

import { useAuth } from "@/components/auth/authContext";
import { logout } from "@/lib/frontend/apiClient";
import { buildLoginUrl, LOGIN_REASONS } from "@/lib/frontend/authRedirect";

import { Button } from "@/components/ui/button";
import {
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuItem,
	DropdownMenuLabel,
	DropdownMenuSeparator,
	DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

/**
 * UserStatus (RHL-020)
 *
 * Updated responsibilities (RHL-032):
 * - Display minimal session info in the TopNav.
 * - Act as a user action menu trigger (settings/logout).
 *
 * UX rule:
 * - All user-facing strings must be German.
 */
export default function UserStatus() {
	const { status, user } = useAuth();

	function formatRole(role) {
		if (role === "branch") return "Niederlassung";
		if (role === "admin") return "Admin";
		if (role === "dev") return "Entwicklung";
		return role ? String(role) : "Unbekannt";
	}

	const isAuthenticated = status === "authenticated" && user;

	let text = "Nicht geladen";
	if (status === "loading") text = "Lädt…";
	if (isAuthenticated) {
		const roleLabel = formatRole(user.role);
		text = user.branchId ? `${roleLabel} (${user.branchId})` : roleLabel;
	}
	if (status === "unauthenticated") text = "Abgemeldet";
	if (status === "error") text = "Fehler";

	async function handleLogout() {
		try {
			await logout();
		} catch (err) {
			// Logout is idempotent; we still redirect to login for predictable UX.
			console.error("[UserStatus] logout failed:", err);
		}

		const loginUrl = buildLoginUrl({ reason: LOGIN_REASONS.LOGGED_OUT });
		window.location.replace(loginUrl);
	}

	return (
		<DropdownMenu>
			<DropdownMenuTrigger asChild>
				<Button
					type="button"
					variant="ghost"
					size="sm"
					className="gap-2"
					aria-label="Benutzermenü öffnen"
					title="Benutzermenü"
				>
					<User className="h-4 w-4" aria-hidden="true" />

					{/* Keep the label visible on md+ like before, but keep menu accessible on mobile */}
					<span className="hidden text-xs md:inline">{text}</span>
				</Button>
			</DropdownMenuTrigger>

			<DropdownMenuContent align="end" className="min-w-56">
				<DropdownMenuLabel>Benutzer</DropdownMenuLabel>

				<div className="px-2 pb-2 text-xs text-muted-foreground">
					{isAuthenticated
						? `Angemeldet als: ${text}`
						: "Keine aktive Sitzung."}
				</div>

				<DropdownMenuSeparator />

				<DropdownMenuItem asChild disabled={!isAuthenticated}>
					<Link href="/settings" className="flex w-full items-center gap-2">
						<Settings className="h-4 w-4" aria-hidden="true" />
						Einstellungen
					</Link>
				</DropdownMenuItem>

				<DropdownMenuItem disabled title="Kommt später">
					<KeyRound className="h-4 w-4" aria-hidden="true" />
					Passwort ändern
				</DropdownMenuItem>

				<DropdownMenuSeparator />

				<DropdownMenuItem
					variant="destructive"
					disabled={!isAuthenticated}
					onSelect={(e) => {
						e.preventDefault();
						handleLogout();
					}}
				>
					<LogOut className="h-4 w-4" aria-hidden="true" />
					Abmelden
				</DropdownMenuItem>
			</DropdownMenuContent>
		</DropdownMenu>
	);
}
