"use client";

import React from "react";
import { usePathname } from "next/navigation";
import { LifeBuoy } from "lucide-react";
import { useAuth } from "@/components/auth/authContext";

import ChangePasswordCard from "@/components/profile/ChangePasswordCard";
import { buildSupportMailto } from "@/lib/frontend/support/supportMailto";

import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
	Card,
	CardHeader,
	CardTitle,
	CardDescription,
	CardContent,
} from "@/components/ui/card";

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

export default function ProfilePage() {
	const pathname = usePathname() || "/profile";
	const { status, user } = useAuth();
	const [passwordChangedSuccess, setPasswordChangedSuccess] =
		React.useState(false);

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

	const roleLabel = isAuthenticated ? formatRole(user.role) : "—";
	const branchLabel = isAuthenticated ? user.branchId || "—" : "—";
	const emailLabel = isAuthenticated ? user.email || "—" : "—";
	const userIdLabel = isAuthenticated ? user.userId || "—" : "—";
	const mustChangePassword =
		isAuthenticated && user.mustChangePassword === true;
	const currentUrl = typeof window !== "undefined" ? window.location.href : "";
	const userAgent = typeof navigator !== "undefined" ? navigator.userAgent : "";

	const supportMailto = React.useMemo(() => {
		return buildSupportMailto({
			user: isAuthenticated ? user : null,
			pathname,
			currentUrl,
			userAgent,
		});
	}, [isAuthenticated, user, pathname, currentUrl, userAgent]);

	React.useEffect(() => {
		if (mustChangePassword) {
			setPasswordChangedSuccess(false);
		}
	}, [mustChangePassword]);

	return (
		<div className="space-y-4 w-1/2 mx-auto">
			<div className="space-y-1">
				<h1 className="text-2xl font-semibold tracking-tight">Profil</h1>
				<p className="text-sm text-muted-foreground">
					Konto- und Zugangseinstellungen.
				</p>
			</div>

			{mustChangePassword ? (
				<Alert variant="destructive">
					<AlertTitle>Passwortänderung erforderlich</AlertTitle>
					<AlertDescription>
						Sie müssen Ihr Passwort ändern, bevor Sie fortfahren können.
					</AlertDescription>
				</Alert>
			) : null}

			{!mustChangePassword && passwordChangedSuccess ? (
				<Alert className="border-emerald-500/40 bg-emerald-50 text-emerald-900 dark:border-emerald-400/40 dark:bg-emerald-950/40 dark:text-emerald-100">
					<AlertTitle>Passwort erfolgreich geändert</AlertTitle>
					<AlertDescription className="text-emerald-800 dark:text-emerald-200">
						Ihr Passwort wurde erfolgreich aktualisiert. Sie können jetzt normal
						weiterarbeiten.
					</AlertDescription>
				</Alert>
			) : null}

			<Card>
				<CardHeader>
					<CardTitle>Konto</CardTitle>
					<CardDescription>Aktuelle Sitzungsinformationen.</CardDescription>
				</CardHeader>

				<CardContent className="grid gap-3 text-sm">
					<div className="flex items-center justify-between gap-4">
						<span className="text-muted-foreground">Rolle</span>
						<span>{roleLabel}</span>
					</div>

					<div className="flex items-center justify-between gap-4">
						<span className="text-muted-foreground">Niederlassung</span>
						<span>{branchLabel}</span>
					</div>

					<div className="flex items-center justify-between gap-4">
						<span className="text-muted-foreground">E-Mail</span>
						<span className="truncate">{emailLabel}</span>
					</div>

					<div className="flex items-center justify-between gap-4">
						<span className="text-muted-foreground">User ID</span>
						<span className="truncate">{userIdLabel}</span>
					</div>

					<p className="pt-1 text-xs text-muted-foreground">
						Die E-Mail wird zentral verwaltet. Für Änderungen wenden Sie sich an
						die IT.
					</p>
				</CardContent>
			</Card>

			<ChangePasswordCard
				onPasswordChangeSuccess={() => setPasswordChangedSuccess(true)}
			/>

			<Card>
				<CardHeader>
					<CardTitle>Support</CardTitle>
					<CardDescription>
						Bei Fragen oder Problemen können Sie direkt den Support
						kontaktieren.
					</CardDescription>
				</CardHeader>

				<CardContent>
					<div className="flex justify-start">
						<Button variant="outline" asChild>
							<a href={supportMailto}>
								<LifeBuoy className="h-4 w-4" aria-hidden="true" />
								Support kontaktieren
							</a>
						</Button>
					</div>
				</CardContent>
			</Card>

			{!isAuthenticated ? (
				<p className="text-xs text-muted-foreground">
					Hinweis: Profilfunktionen sind nur verfügbar, wenn Sie angemeldet
					sind.
				</p>
			) : null}
		</div>
	);
}
