import React from "react";

import {
	ROLE_LABELS_DE,
	formatDateTimeDe,
} from "@/components/admin/users/usersUi";

import EditUserDialog from "@/components/admin/users/EditUserDialog";
import DeleteUserDialog from "@/components/admin/users/DeleteUserDialog";

import { Badge } from "@/components/ui/badge";
import {
	Table,
	TableBody,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";

export default function UsersTable({ items, disabled = false, onUserUpdated }) {
	const list = Array.isArray(items) ? items : [];

	return (
		<Table className="min-w-[76rem] table-fixed">
			<TableHeader>
				<TableRow>
					<TableHead className="w-44">Benutzername</TableHead>
					<TableHead className="w-56">E-Mail</TableHead>
					<TableHead className="w-40">Rolle</TableHead>
					<TableHead className="w-20">NL</TableHead>
					<TableHead className="w-40">Passwortwechsel</TableHead>
					<TableHead className="w-40">Aktualisiert</TableHead>
					<TableHead className="sticky right-0 z-20 w-20 bg-card text-right">
						Aktion
					</TableHead>
				</TableRow>
			</TableHeader>

			<TableBody>
				{list.map((u) => {
					const must = Boolean(u.mustChangePassword);

					return (
						<TableRow key={u.id}>
							<TableCell className="truncate font-medium" title={u.username}>
								{u.username}
							</TableCell>

							<TableCell className="min-w-0">
								<span className="block truncate" title={u.email}>
									{u.email}
								</span>
							</TableCell>

							<TableCell>
								<Badge variant="secondary">
									{ROLE_LABELS_DE[u.role] || u.role}
								</Badge>
							</TableCell>

							<TableCell>
								{u.branchId ? (
									<Badge variant="outline">{u.branchId}</Badge>
								) : (
									<span className="text-muted-foreground">—</span>
								)}
							</TableCell>

							<TableCell>
								{must ? (
									<Badge variant="destructive">Erforderlich</Badge>
								) : (
									<Badge variant="secondary">Nein</Badge>
								)}
							</TableCell>

							<TableCell className="text-xs text-muted-foreground">
								{formatDateTimeDe(u.updatedAt)}
							</TableCell>

							<TableCell className="sticky right-0 z-10 w-20 bg-card text-right">
								<div className="flex items-center justify-end gap-1">
									<EditUserDialog
										user={u}
										disabled={disabled}
										onUpdated={onUserUpdated}
									/>
									<DeleteUserDialog
										user={u}
										disabled={disabled}
										onDeleted={onUserUpdated}
									/>
								</div>
							</TableCell>
						</TableRow>
					);
				})}
			</TableBody>
		</Table>
	);
}
