"use client"; import { useMemo, useState } from "react"; import { useRouter } from "next/navigation"; import { Check, ChevronDown, PlusIcon, TrashIcon } from "lucide-react"; import { Combobox, type ComboboxOption } from "@/components/ui/combobox"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "@/components/ui/command"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import type { ReservationOptions } from "@/lib/operations/reservationOptions"; import { createReservation } from "@/app/(frontend)/operations/reservations/actions"; interface CreateReservationDialogProps { options: ReservationOptions; canManageLogistics: boolean; currentUserId: number; /** Trigger only renders for users who hold operation-reservations:create. */ canCreate: boolean; /** Pre-select vehicles (e.g. "Reserve for operation" from the garage). */ initialVehicleIds?: number[]; /** Override the trigger button text. */ triggerLabel?: string; } interface CargoLine { resourceId: string; amount: string; } /** * Searchable multi-value picker built on the same Command/Popover primitives as * the site Combobox, which is single-value only. Selections persist in a number * array; the popover stays as wide as the trigger. */ function MultiSelect({ label, options, selected, onChange, disabled, placeholder = "None selected", }: { label: string; options: ComboboxOption[]; selected: number[]; onChange: (value: number[]) => void; disabled?: boolean; placeholder?: string; }) { const [open, setOpen] = useState(false); const selectedLabels = useMemo( () => options.filter((o) => selected.includes(Number(o.value))).map((o) => o.label), [options, selected], ); return ( !disabled && setOpen(next)}> {selectedLabels.length > 0 ? selectedLabels.join(", ") : placeholder} Nothing found. {options.map((option) => { const value = Number(option.value); const isSelected = selected.includes(value); return ( { onChange( isSelected ? selected.filter((v) => v !== value) : [...selected, value].sort((a, b) => a - b), ); }} > {option.label} ); })} ); } export function CreateReservationDialog({ options, canManageLogistics, currentUserId, canCreate, initialVehicleIds, triggerLabel, }: CreateReservationDialogProps) { const router = useRouter(); const [open, setOpen] = useState(false); const [reservationKey, setReservationKey] = useState(""); const [operationId, setOperationId] = useState(""); const [missionId, setMissionId] = useState(""); const [personnel, setPersonnel] = useState([]); const [vehicles, setVehicles] = useState(initialVehicleIds ?? []); const [originId, setOriginId] = useState(""); const [destinationId, setDestinationId] = useState(""); const [cargoLines, setCargoLines] = useState([]); const [budgetAccountId, setBudgetAccountId] = useState(""); const [budgetAmount, setBudgetAmount] = useState(""); const [expiresAt, setExpiresAt] = useState(""); const [error, setError] = useState(null); const [submitting, setSubmitting] = useState(false); const missionOptions: ComboboxOption[] = options.upcomingMissions.map((m) => ({ value: String(m.id), label: m.name + (m.codeName ? ` (${m.codeName})` : ""), })); const vehicleOptions: ComboboxOption[] = options.vehicles.map((v) => ({ value: String(v.id), label: v.name, hint: `${v.fuelPct}% fuel`, })); const rosterOptions: ComboboxOption[] = options.rosterUsers.map((u) => ({ value: String(u.id), label: u.displayName, })); const originOptions: ComboboxOption[] = options.originStructures.map((s) => ({ value: String(s.id), label: s.name, })); const destinationOptions: ComboboxOption[] = options.destinationStructures.map((s) => ({ value: String(s.id), label: s.name, })); const budgetOptions: ComboboxOption[] = options.budgetAccounts.map((a) => ({ value: String(a.id), label: a.name, hint: a.type, })); const originStock = originId ? options.stockByOrigin[originId] ?? [] : []; function reset() { setReservationKey(""); setOperationId(""); setMissionId(""); setPersonnel([]); setVehicles(initialVehicleIds ?? []); setOriginId(""); setDestinationId(""); setCargoLines([]); setBudgetAccountId(""); setBudgetAmount(""); setExpiresAt(""); setError(null); } function updateCargo(index: number, patch: Partial) { setCargoLines((lines) => lines.map((line, i) => (i === index ? { ...line, ...patch } : line)), ); } function addCargoLine() { setCargoLines((lines) => [...lines, { resourceId: "", amount: "" }]); } function removeCargoLine(index: number) { setCargoLines((lines) => lines.filter((_, i) => i !== index)); } /** * Client-side sanity checks only. The server action re-validates every limit * and is the source of truth; these give the form immediate feedback before * the request goes out. */ function clientErrors(): string[] { const errors: string[] = []; if (!reservationKey.trim()) errors.push("A reservation key is required."); if (!operationId.trim()) errors.push("An operation id is required."); for (const [i, line] of cargoLines.entries()) { const amount = Number(line.amount); if (line.resourceId && (!Number.isInteger(amount) || amount <= 0)) { errors.push(`Cargo amount on line ${i + 1} must be a positive integer.`); } } if (cargoLines.some((l) => l.resourceId) && !originId) { errors.push("An origin structure is required when cargo is reserved."); } if (budgetAmount && (!Number.isInteger(Number(budgetAmount)) || Number(budgetAmount) <= 0)) { errors.push("Budget amount must be a positive integer."); } return errors; } async function handleSubmit() { const problems = clientErrors(); if (problems.length > 0) { setError(problems.join(" ")); return; } setSubmitting(true); setError(null); const result = await createReservation({ reservationKey: reservationKey.trim(), operationId: operationId.trim(), actorId: currentUserId, ...(missionId ? { missionId: Number(missionId) } : {}), ...(personnel.length ? { personnel: personnel.map((id) => ({ userId: id })) } : {}), ...(vehicles.length ? { vehicleIds: [...vehicles] } : {}), ...(cargoLines .filter((l) => l.resourceId && Number(l.amount) > 0) .length ? { cargo: cargoLines .filter((l) => l.resourceId && Number(l.amount) > 0) .map((l) => ({ resourceId: Number(l.resourceId), amount: Number(l.amount) })), } : {}), ...(budgetAmount ? { budget: { accountId: Number(budgetAccountId), amount: Number(budgetAmount) } } : {}), ...(originId ? { originId: Number(originId) } : {}), ...(destinationId ? { destinationId: Number(destinationId) } : {}), ...(expiresAt ? { expiresAt: new Date(expiresAt).toISOString() } : {}), }); if (result.success) { setOpen(false); reset(); router.refresh(); } else { // Surface the engine's error string verbatim; the server action never // rewords the allocation-rejected message. setError(result.error ?? "Failed to create reservation."); setSubmitting(false); } } return ( { setOpen(next); if (!next) reset(); }}> {canCreate ? ( ) : null} Reserve Operation Assets earmark people, vehicles, cargo, and treasury budget against an operation. Capacity and funds are enforced server-side.
setReservationKey(e.target.value)} placeholder="e.g. op-24-alpha" />
setOperationId(e.target.value)} placeholder="e.g. operation-id" />
{!canManageLogistics ? ( ) : (
)}
{canManageLogistics ? (
{cargoLines.length === 0 ? (

No cargo reserved.

) : (
{cargoLines.map((line, index) => (
{originStock.length > 0 ? ( updateCargo(index, { resourceId: v })} searchPlaceholder="Search resources..." emptyMessage="Nothing stored at this origin." options={originStock.map((s) => ({ value: String(s.resourceId), label: s.resourceName, hint: `${s.amount.toLocaleString()} available`, }))} /> ) : (

Select an origin to choose resources.

)}
updateCargo(index, { amount: e.target.value })} />
))}
)}
) : (

Disabled until logistics access is granted.

)}
{canManageLogistics ? (
setBudgetAmount(e.target.value)} />
) : ( )}
setExpiresAt(e.target.value)} />
{error &&

{error}

}
); } /** * Wrapper that disables a form section for users without logistics access and * shows why. UX-only gating; the server action is the source of truth. */ function SectionGated({ hint, children, }: { hint?: string; children: React.ReactNode; }) { return (
{hint ?

{hint}

: null}
{children}
); }