"use client";

import React from "react";
import { Loader2, RefreshCw } from "lucide-react";

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

/**
 * AuthGate
 *
 * Renders auth-related states *inside* the AppShell main area to avoid "blank spinner" screens.
 *
 * Why this exists:
 * - AuthProvider owns the session check and provides AuthContext.
 * - We want the AppShell frame (TopNav/sidebar) to remain stable while auth checks run.
 * - This component decides what the user sees inside the main content area.
 *
 * UX rule:
 * - All user-facing strings are German.
 *
 * @param {{ children: React.ReactNode }} props
 */
export default function AuthGate({ children }) {
	const { status, error, retry } = useAuth();

	const canRetry = typeof retry === "function";

	if (status === "authenticated") {
		return children;
	}

	if (status === "error") {
		return (
			<Card>
				<CardHeader>
					<CardTitle>Sitzungsprüfung fehlgeschlagen</CardTitle>
					<CardDescription>
						Die Sitzung konnte nicht geprüft werden.
					</CardDescription>
				</CardHeader>

				<CardContent className="space-y-3">
					<Alert variant="destructive">
						<AlertTitle>Fehler</AlertTitle>
						<AlertDescription>
							{error ||
								"Bitte prüfen Sie Ihre Verbindung und versuchen Sie es erneut."}
						</AlertDescription>
					</Alert>
				</CardContent>

				<CardFooter className="flex flex-col gap-2 sm:flex-row sm:justify-end">
					<Button
						type="button"
						variant="outline"
						onClick={() => {
							if (canRetry) retry();
							else window.location.reload();
						}}
					>
						<RefreshCw className="h-4 w-4" />
						Erneut versuchen
					</Button>
				</CardFooter>
			</Card>
		);
	}

	// "unauthenticated" -> redirect happens in AuthProvider.
	if (status === "unauthenticated") {
		return (
			<Card>
				<CardHeader>
					<CardTitle>Weiterleitung</CardTitle>
					<CardDescription>
						Sie werden zum Login weitergeleitet.
					</CardDescription>
				</CardHeader>

				<CardContent>
					<div className="flex items-center gap-3 text-sm text-muted-foreground">
						<Loader2 className="h-4 w-4 animate-spin" />
						<span>Weiterleitung zum Login…</span>
					</div>
				</CardContent>
			</Card>
		);
	}

	// Default: loading (or unknown)
	return (
		<Card>
			<CardHeader>
				<CardTitle>Sitzung wird geprüft</CardTitle>
				<CardDescription>Bitte warten…</CardDescription>
			</CardHeader>

			<CardContent>
				<div className="flex items-center gap-3 text-sm text-muted-foreground">
					<Loader2 className="h-4 w-4 animate-spin" />
					<span>Sitzung wird geprüft…</span>
				</div>
			</CardContent>
		</Card>
	);
}
