/** ApplicationsTab — read-only Authentik application directory. */
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import {
	Table,
	TableBody,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";
import { useAuthentikApplications } from "../../hooks/useAuthentik";
import type { ServiceInstance } from "../../types";

export function ApplicationsTab({ instance }: { instance: ServiceInstance }) {
	const { data, isLoading } = useAuthentikApplications(instance.id);
	const applications = data?.items ?? [];
	return (
		<div className="flex flex-col gap-3">
			<Alert>
				<AlertDescription>
					Application metadata only; providers, outposts, policies, and
					effective access evaluation are not shown.
				</AlertDescription>
			</Alert>
			{data?.error ? (
				<Alert variant="destructive">
					<AlertDescription>{data.error}</AlertDescription>
				</Alert>
			) : null}
			<div className="rounded-lg border">
				<Table>
					<TableHeader>
						<TableRow>
							<TableHead>Application</TableHead>
							<TableHead>Slug</TableHead>
							<TableHead>Launch URL</TableHead>
						</TableRow>
					</TableHeader>
					<TableBody>
						{isLoading && applications.length === 0 ? (
							<TableRow>
								<TableCell colSpan={3}>
									<Skeleton className="h-5 w-full" />
								</TableCell>
							</TableRow>
						) : null}
						{!isLoading && applications.length === 0 ? (
							<TableRow>
								<TableCell colSpan={3} className="text-muted-foreground">
									No applications found.
								</TableCell>
							</TableRow>
						) : null}
						{applications.map((application) => (
							<TableRow
								key={application.id || application.slug || application.name}
							>
								<TableCell className="font-medium">
									{application.name}
								</TableCell>
								<TableCell className="font-mono text-xs text-muted-foreground">
									{application.slug || "—"}
								</TableCell>
								<TableCell className="max-w-sm truncate text-muted-foreground">
									{application.launch_url || "—"}
								</TableCell>
							</TableRow>
						))}
					</TableBody>
				</Table>
			</div>
			{data && data.total > applications.length ? (
				<p className="text-sm text-muted-foreground">
					Showing the first {applications.length} of {data.total} applications.
				</p>
			) : null}
		</div>
	);
}
