"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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select"; 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 { useCompanyScope } from "@/app/lib/CompanyScope"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import type { AdminUser } from "@/app/lib/types"; import { PasswordFields } from "./PasswordFields"; // 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; } /** On create the payload also carries the admin-typed first password and its confirmation. */ export type UserFormPayload = AdminUser & { password?: string; confirmPassword?: string; companyId?: number; superAdmin?: boolean }; export interface UserFormProps { initial?: AdminUser; onSubmit: (payload: UserFormPayload) => Promise; submitLabel?: string; /** Create only: ask for the first password (the user must change it at first sign-in). */ withPassword?: boolean; } export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserFormProps) { const t = useT(); const { id: myId, isSuper } = useAdminAuth(); const scope = useCompanyScope(); // Super admins pick the new user's company on create; "super" makes another company-less super admin. const showCompany = isSuper === true && initial?.id == null; const [company, setCompany] = useState(scope.companyId ? String(scope.companyId) : ""); // 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 [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); 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"); if (showCompany && !company) errors.company = t("ChooseCompany"); else if (showCompany && company === "super" && !selectedRoleIds.has(1)) errors.company = t("SuperAdminNeedsRole"); if (withPassword && !password) errors.password = t("UsrPasswordRequired"); else if (withPassword && password !== confirmPassword) errors.confirmPassword = t("UsrPasswordMismatch"); 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 })), ...(withPassword ? { password, confirmPassword } : {}), ...(showCompany ? (company === "super" ? { superAdmin: true } : { companyId: Number(company) }) : {}), }); } 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}

)}
{showCompany && (
{fieldErrors.company && (

{fieldErrors.company}

)}
)} {withPassword && ( )}
{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")}

); }