/** UsersTab — Authentik access metadata, not an effective-permissions calculation. */
import { useState } from "react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
	Table,
	TableBody,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";
import type { ServiceInstance } from "../../types";
import { useAuthentikAccessSummary } from "../../hooks/useAuthentik";

const PAGE_SIZE = 25;

export function UsersTab({ instance }: { instance: ServiceInstance }) {
	const [search, setSearch] = useState("");
	const [page, setPage] = useState(1);
	const [committedSearch, setCommittedSearch] = useState("");
	const { data, isLoading } = useAuthentikAccessSummary(instance.id, {
		search: committedSearch,
		page,
		page_size: PAGE_SIZE,
	});
	const users = data?.items ?? [];
	const total = data?.total ?? 0;
	const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));

	function handleSearch() {
		setPage(1);
		setCommittedSearch(search);
	}

	return (
		<div className="flex flex-col gap-3">
			<Alert>
				<AlertDescription>
					Shows Authentik group membership and explicit staff/superuser flags.
					This is access metadata, not a complete effective-authorization
					calculation.
				</AlertDescription>
			</Alert>
			{data?.error ? (
				<Alert variant="destructive">
					<AlertDescription>{data.error}</AlertDescription>
				</Alert>
			) : null}
			<div className="flex items-center gap-2">
				<Input
					placeholder="Search users…"
					value={search}
					onChange={(event) => setSearch(event.target.value)}
					onKeyDown={(event) => {
						if (event.key === "Enter") handleSearch();
					}}
					className="max-w-xs"
				/>
				<Button variant="outline" onClick={handleSearch}>
					Search
				</Button>
			</div>
			<div className="rounded-lg border">
				<Table>
					<TableHeader>
						<TableRow>
							<TableHead>Name</TableHead>
							<TableHead>Username</TableHead>
							<TableHead>Groups</TableHead>
							<TableHead>Privileges</TableHead>
							<TableHead>Status</TableHead>
						</TableRow>
					</TableHeader>
					<TableBody>
						{isLoading && users.length === 0 ? (
							<TableRow>
								<TableCell colSpan={5} className="text-muted-foreground">
									Loading…
								</TableCell>
							</TableRow>
						) : null}
						{!isLoading && users.length === 0 ? (
							<TableRow>
								<TableCell colSpan={5} className="text-muted-foreground">
									No users found.
								</TableCell>
							</TableRow>
						) : null}
						{users.map((user) => (
							<TableRow key={user.id || user.username}>
								<TableCell className="font-medium">
									{user.name || "—"}
								</TableCell>
								<TableCell>{user.username || "—"}</TableCell>
								<TableCell>
									<div className="flex max-w-sm flex-wrap gap-1">
										{user.groups.length ? (
											user.groups.map((group) => (
												<Badge
													key={group.id}
													variant={group.known ? "secondary" : "destructive"}
												>
													{group.name}
												</Badge>
											))
										) : (
											<span className="text-muted-foreground">None</span>
										)}
									</div>
								</TableCell>
								<TableCell>
									<div className="flex flex-wrap gap-1">
										{user.is_superuser ? (
											<Badge variant="destructive">Superuser</Badge>
										) : null}
										{user.is_staff ? <Badge>Staff</Badge> : null}
										{!user.is_superuser && !user.is_staff ? (
											<span className="text-muted-foreground">None</span>
										) : null}
									</div>
								</TableCell>
								<TableCell>
									<Badge variant={user.is_active ? "default" : "secondary"}>
										{user.is_active ? "Active" : "Inactive"}
									</Badge>
								</TableCell>
							</TableRow>
						))}
					</TableBody>
				</Table>
			</div>
			{total > 0 ? (
				<div className="flex items-center justify-between text-sm text-muted-foreground">
					<span>
						{total} user{total === 1 ? "" : "s"} · Page {page} of {totalPages}
					</span>
					<div className="flex gap-1">
						<Button
							variant="outline"
							size="sm"
							onClick={() => setPage((current) => Math.max(1, current - 1))}
							disabled={page <= 1}
						>
							Previous
						</Button>
						<Button
							variant="outline"
							size="sm"
							onClick={() =>
								setPage((current) => Math.min(totalPages, current + 1))
							}
							disabled={page >= totalPages}
						>
							Next
						</Button>
					</div>
				</div>
			) : null}
		</div>
	);
}
