"use client"; import { useEffect, useMemo, useState } from "react"; import { useRouter } from "next/navigation"; import { toast } from "sonner"; import { ArrowLeftRightIcon, Loader2Icon } from "lucide-react"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { Combobox } from "@/components/ui/combobox"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Skeleton } from "@/components/ui/skeleton"; import { Textarea } from "@/components/ui/textarea"; import { requestTransfer } from "@/app/(frontend)/transfers/actions"; import { parseAssignmentPage, relationId, type AccountAssignment, type TransferAssignmentSummary, } from "@/components/frontend/transfers/transferTypes"; interface RequestTransferDialogProps { readonly currentAssignments: readonly AccountAssignment[]; readonly currentUserId: number; } function isMemberOf(assignment: TransferAssignmentSummary, userId: number): boolean { if (relationId(assignment.leader) === userId) return true; return (assignment.members ?? []).some((member) => relationId(member) === userId); } export function RequestTransferDialog({ currentAssignments, currentUserId, }: RequestTransferDialogProps) { const router = useRouter(); const [internalOpen, setInternalOpen] = useState(false); const [sourceId, setSourceId] = useState(""); const [destinationId, setDestinationId] = useState(""); const [destinations, setDestinations] = useState([]); const [note, setNote] = useState(""); const [loadingDestinations, setLoadingDestinations] = useState(false); const [pending, setPending] = useState(false); const [error, setError] = useState(null); const requestableAssignments = useMemo( () => currentAssignments.filter((assignment) => assignment.leaderId !== currentUserId), [currentAssignments, currentUserId], ); const currentAssignmentIds = useMemo( () => new Set(currentAssignments.map((assignment) => assignment.id)), [currentAssignments], ); const currentAssignmentKey = currentAssignments.map((assignment) => assignment.id).join(","); const open = internalOpen; useEffect(() => { if (!requestableAssignments.some((assignment) => String(assignment.id) === sourceId)) { setSourceId(String(requestableAssignments[0]?.id ?? "")); } }, [requestableAssignments, sourceId]); useEffect(() => { if (!open) return; const controller = new AbortController(); setLoadingDestinations(true); setError(null); async function loadDestinations() { try { const response = await fetch("/api/assignments?depth=1&limit=100&sort=name", { signal: controller.signal, cache: "no-store", }); if (!response.ok) throw new Error("Could not load eligible assignments."); const body: unknown = await response.json(); const parsed = parseAssignmentPage(body); if (!parsed) throw new Error("The assignment response was invalid."); const available = parsed.filter( (assignment) => !currentAssignmentIds.has(assignment.id) && !isMemberOf(assignment, currentUserId), ); setDestinations(available); setDestinationId((previous) => available.some((assignment) => String(assignment.id) === previous) ? previous : String(available[0]?.id ?? ""), ); } catch (caughtError) { if (caughtError instanceof DOMException && caughtError.name === "AbortError") return; setError( caughtError instanceof Error ? caughtError.message : "Could not load eligible assignments.", ); } finally { if (!controller.signal.aborted) setLoadingDestinations(false); } } void loadDestinations(); return () => controller.abort(); }, [currentAssignmentIds, currentAssignmentKey, currentUserId, open]); function reset() { setDestinationId(""); setDestinations([]); setNote(""); setError(null); setPending(false); } async function handleSubmit(event: React.FormEvent) { event.preventDefault(); const fromAssignmentId = Number(sourceId); const toAssignmentId = Number(destinationId); if (!Number.isInteger(fromAssignmentId) || fromAssignmentId <= 0) { setError("Choose a current assignment."); return; } if (!Number.isInteger(toAssignmentId) || toAssignmentId <= 0) { setError("Choose a destination assignment."); return; } if (fromAssignmentId === toAssignmentId) { setError("Choose an assignment different from your current one."); return; } setPending(true); setError(null); try { const result = await requestTransfer({ fromAssignmentId, toAssignmentId, note: note.trim() || undefined, }); if (!result.success) { setError(result.error ?? "Could not submit the transfer request."); return; } toast.success("Transfer request submitted"); setInternalOpen(false); reset(); router.refresh(); } catch (caughtError) { setError( caughtError instanceof Error ? caughtError.message : "Could not submit the transfer request.", ); } finally { setPending(false); } } return ( { setInternalOpen(nextOpen); if (!nextOpen) reset(); }} > Request assignment transfer Choose an assignment you are not already part of. Leaders cannot request transfers.
({ value: String(assignment.id), label: assignment.callsign ? `${assignment.name} · ${assignment.callsign}` : assignment.name, }))} />
{loadingDestinations ? ( ) : destinations.length > 0 ? ( ({ value: String(assignment.id), label: assignment.callsign ? `${assignment.name} · ${assignment.callsign}` : assignment.name, }))} /> ) : ( No eligible destination assignments are available right now. )}