"use client"; import { useEffect, useMemo, useState, type FormEvent } from "react"; import { Check, ChevronsUpDown, X } from "lucide-react"; import { Badge } from "@/app/components/ui/badge"; import { Button } from "@/app/components/ui/button"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "@/app/components/ui/command"; import { Popover, PopoverContent, PopoverTrigger } from "@/app/components/ui/popover"; 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 { listAdminLocations } from "@/app/lib/services/adminLocations"; import { listSellableCountries } from "@/app/lib/services/sellableCountries"; import { listEvents } from "@/app/lib/services/adminEvents"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import type { AdminUser, SellableCountry } from "@/app/lib/types"; // Shared create/edit form for /users/new and /users/[id] (plan: "Build the admin // add/edit-user form"). Roles/Branch pickers are populated from the existing CRUD // list endpoints; Branch is restricted to type "B" (branch-level) location nodes // only — a user is never assigned a country/region/global node. const NONE = "none"; // 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; } interface BranchOption { id: number; name: string; code: string; } interface EventOption { id: number; name: string; code: string; closed: boolean; } export interface UserFormProps { initial?: AdminUser; onSubmit: (payload: AdminUser) => Promise; submitLabel?: string; } export function UserForm({ initial, onSubmit, submitLabel }: UserFormProps) { const t = useT(); 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 [branchId, setBranchId] = useState(initial?.branch ? String(initial.branch.id) : NONE); const [eventId, setEventId] = useState(initial?.event?.id ?? null); const [eventOpen, setEventOpen] = useState(false); const [eventOptions, setEventOptions] = useState([]); const [roleOptions, setRoleOptions] = useState([]); const [branchOptions, setBranchOptions] = useState([]); const [countryOptions, setCountryOptions] = useState([]); const [allCountries, setAllCountries] = useState(!initial?.countryScope?.length); const [selectedCountries, setSelectedCountries] = useState>( () => new Set(initial?.countryScope ?? []), ); 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); Promise.all([ listAdminRoles(), listAdminLocations(), listSellableCountries().catch(() => [] as SellableCountry[]), ]) .then(([roles, locations, countries]) => { if (cancelled) return; setCountryOptions(countries); setRoleOptions( roles .filter((r): r is typeof r & { id: number } => r.id != null) .map((r) => ({ id: r.id, name: r.name })), ); setBranchOptions( locations .filter((l) => l.type === "B") .map((l) => ({ id: l.id, name: l.name, code: l.code })), ); }) .catch((err: unknown) => { if (!cancelled) { setPickersError(err instanceof Error ? err.message : "SetupLoadOptionsFailed"); } }) .finally(() => { if (!cancelled) setLoadingPickers(false); }); return () => { cancelled = true; }; }, []); // Events load separately so a failure never blocks the rest of the form. useEffect(() => { let cancelled = false; listEvents() .then((events) => { if (!cancelled) setEventOptions( events.map((e) => ({ id: Number(e.id), name: e.name, code: e.code, closed: e.status === "C" })), ); }) .catch(() => {}); return () => { cancelled = true; }; }, []); const initialEventId = initial?.event?.id ?? null; const visibleEvents = eventOptions.filter((e) => !e.closed || e.id === initialEventId); const selectedEvent = eventOptions.find((e) => e.id === eventId); function toggleRole(id: number) { setSelectedRoleIds((prev) => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); } function toggleCountry(code: string) { setSelectedCountries((prev) => { const next = new Set(prev); if (next.has(code)) next.delete(code); else next.add(code); return next; }); } const showCountryScope = countryOptions.length > 1; 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"); // service-system.user.branchid is NOT NULL: a user without a branch cannot be saved. if (branchId === NONE) errors.branch = t("UsrBranchRequired"); if (showCountryScope && !allCountries && selectedCountries.size === 0) errors.countryScope = t("UsrCountryScopeRequired"); 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 })), branch: branchId !== NONE ? { id: Number(branchId) } : undefined, // Omit when never tied, so an untied user keeps its stored scope untouched. // Omit with one sellable country, so the stored scope is kept untouched. ...(showCountryScope && { countryScope: allCountries ? null : [...selectedCountries] }), event: eventId !== null || initialEventId !== null ? { id: eventId } : undefined, }); } 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)} disabled={saving} 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)} />
)) )}
{showCountryScope && (
{t("UsrCountryScope")}
setAllCountries(v === true)} />
{!allCountries && (
{[ ...countryOptions, // A stored code that is no longer sellable stays listed so it can be unticked. ...[...selectedCountries] .filter((code) => !countryOptions.some((o) => o.code === code)) .map((code) => ({ code, name: code })), ].map((c) => (
toggleCountry(c.code)} />
))}
)} {fieldErrors.countryScope && (

{fieldErrors.countryScope}

)}
)}
{fieldErrors.branch && (

{fieldErrors.branch}

)}
{t("UiNoResults")} {[{ id: null, name: t("UsrEventNone"), code: "" }, ...visibleEvents].map((e) => ( { setEventId(e.id); setEventOpen(false); }} > ))}

{t("UsrEventHint")}

{t("UsrDisabledHint")}

); }