"use client"; import { useEffect, useMemo, useState, type FormEvent } from "react"; import { X } from "lucide-react"; import { Badge } from "@/app/components/ui/badge"; import { Button } from "@/app/components/ui/button"; import { Checkbox } from "@/app/components/ui/checkbox"; import { Input } from "@/app/components/ui/input"; import { Label } from "@/app/components/ui/label"; import { Switch } from "@/app/components/ui/switch"; import { ErrorState } from "@/app/components/ui/states"; import { roleLabel } from "@/app/lib/roleLabel"; import { Skeleton } from "@/app/components/ui/skeleton"; import { listAdminRoles } from "@/app/lib/services/adminRoles"; import { useAdminAuth } from "@/app/lib/AdminAuthContext"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import type { AdminUser } from "@/app/lib/types"; // Shared create/edit form for /users/new and /users/[id] (plan: "Build the admin // add/edit-user form"). The Roles picker is populated from the admin roles list // endpoint; the backend sets the branch from the creating admin. // Deliberately basic (RFC-exhaustive email validation is out of scope) — mirrors // the "basic email validation" requirement in the plan. const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; interface RoleOption { id: number; name: string; } export interface UserFormProps { initial?: AdminUser; onSubmit: (payload: AdminUser) => Promise; submitLabel?: string; } export function UserForm({ initial, onSubmit, submitLabel }: UserFormProps) { const t = useT(); const { id: myId } = useAdminAuth(); // The server refuses SELF_DEACTIVATION; this keeps the switch from offering it. const isOwnAccount = initial?.id != null && initial.id === myId; const [name, setName] = useState(initial?.name ?? ""); const [surname, setSurname] = useState(initial?.surname ?? ""); const [username, setUsername] = useState(initial?.username ?? ""); const [email, setEmail] = useState(initial?.email ?? ""); const [enabled, setEnabled] = useState(initial?.enabled ?? true); const [selectedRoleIds, setSelectedRoleIds] = useState>( () => new Set((initial?.roles ?? []).map((r) => r.id).filter((id): id is number => id != null)), ); const [roleOptions, setRoleOptions] = useState([]); const [pickersError, setPickersError] = useState(null); const [loadingPickers, setLoadingPickers] = useState(true); const [fieldErrors, setFieldErrors] = useState>({}); const [formError, setFormError] = useState(null); const [saving, setSaving] = useState(false); useEffect(() => { let cancelled = false; // eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the mount-time picker fetch below, which is the actual synchronization. setLoadingPickers(true); setPickersError(null); listAdminRoles() .then((roles) => { if (cancelled) return; setRoleOptions( roles .filter((r): r is typeof r & { id: number } => r.id != null) .map((r) => ({ id: r.id, name: r.name })), ); }) .catch((err: unknown) => { if (!cancelled) { setPickersError(err instanceof Error ? err.message : "SetupLoadOptionsFailed"); } }) .finally(() => { if (!cancelled) setLoadingPickers(false); }); return () => { cancelled = true; }; }, []); function toggleRole(id: number) { setSelectedRoleIds((prev) => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); } const selectedRoles = useMemo( () => roleOptions.filter((r) => selectedRoleIds.has(r.id)), [roleOptions, selectedRoleIds], ); async function handleSubmit(event: FormEvent) { event.preventDefault(); const errors: Record = {}; if (!name.trim()) errors.name = t("UsrNameRequired"); if (!username.trim()) errors.username = t("UsrUsernameRequired"); if (!email.trim()) errors.email = t("UsrEmailRequired"); else if (!EMAIL_RE.test(email.trim())) errors.email = t("UsrEmailInvalid"); setFieldErrors(errors); if (Object.keys(errors).length > 0) return; setFormError(null); setSaving(true); try { await onSubmit({ id: initial?.id, name: name.trim(), surname: surname.trim() || undefined, username: username.trim(), email: email.trim(), enabled, // Only `enabled` gates admin sign-in; status is derived to stay consistent. status: enabled ? "Y" : "N", roles: selectedRoles.map((r) => ({ id: r.id, name: r.name })), }); } catch (err) { setFormError(err instanceof Error ? err.message : "UsrSaveFailed"); } finally { setSaving(false); } } return (
{formError && } {pickersError && }
setName(e.target.value)} disabled={saving} aria-invalid={!!fieldErrors.name} /> {fieldErrors.name && (

{fieldErrors.name}

)}
setSurname(e.target.value)} disabled={saving} />
setUsername(e.target.value)} // The backend ignores username on update, so it is fixed once the user exists. disabled={saving || initial?.id != null} aria-invalid={!!fieldErrors.username} /> {fieldErrors.username && (

{fieldErrors.username}

)}
setEmail(e.target.value)} disabled={saving} aria-invalid={!!fieldErrors.email} /> {fieldErrors.email && (

{fieldErrors.email}

)}
{t("BO_ROLES")} {selectedRoles.length > 0 && (
{selectedRoles.map((r) => ( {roleLabel(r.name)} ))}
)}
{roleOptions.length === 0 ? ( loadingPickers ? (
{t("UsrLoadingRoles")}
) : (

{t("UsrNoRolesAvailable")}

) ) : ( roleOptions.map((role) => (
toggleRole(role.id)} />
)) )}

{t(isOwnAccount ? "UsrOwnAccountHint" : "UsrDisabledHint")}

); }