-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathattendee-list.tsx
More file actions
845 lines (803 loc) · 26.1 KB
/
attendee-list.tsx
File metadata and controls
845 lines (803 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
"use client";
import { useState, useEffect, useMemo, useCallback } from "react";
import {
collection,
getDocs,
limit as fsLimit,
orderBy,
query,
startAfter,
where,
type DocumentSnapshot,
type QueryConstraint,
} from "firebase/firestore";
import { db } from "@/lib/firebase/config";
import {
AdvancedDataTable,
type ColumnDef,
type ColumnMeta,
} from "@/components/shared/advanced-data-table";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { SearchInput } from "@/components/shared/search-input";
import { Users, UserPlus, Trash2, ChevronLeft, ChevronRight } from "lucide-react";
import { toast } from "sonner";
import { useAuth, useIsAdmin, useIsNationalAdmin } from "@/hooks/use-auth";
import { useDebounce } from "@/hooks/use-debounce";
import {
setAttendance,
setAttendeeHours,
addManualAttendee,
removeManualAttendee,
} from "@/lib/firebase/attendees";
import type { Attendee } from "@/types/attendee";
import type { AppEvent } from "@/types/event";
import type { Member } from "@/types/member";
type AttendeeRow = Attendee & { id: string };
const WA_PAGE_SIZE = 50;
// Title-case a search prefix to match how WA stores names ("First Last").
const titleCase = (s: string) =>
s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
export function AttendeeList({ event }: { event: AppEvent & { id: string } }) {
const { user } = useAuth();
const isAdmin = useIsAdmin();
const isNationalAdmin = useIsNationalAdmin();
const [addOpen, setAddOpen] = useState(false);
// ─── WA registrations: paginated server-side ───────────────────────────
const [waRows, setWaRows] = useState<AttendeeRow[]>([]);
const [waLoading, setWaLoading] = useState(true);
const [waPage, setWaPage] = useState(0);
// cursors[i] is the startAfter cursor used to fetch page i. cursors[0] is null.
const [waCursors, setWaCursors] = useState<(DocumentSnapshot | null)[]>([null]);
const [waHasMore, setWaHasMore] = useState(false);
const [waSearch, setWaSearch] = useState("");
const debouncedWaSearch = useDebounce(waSearch, 300);
// Reset pagination when the search changes.
useEffect(() => {
setWaPage(0);
setWaCursors([null]);
}, [debouncedWaSearch]);
useEffect(() => {
let cancelled = false;
setWaLoading(true);
const startCursor = waCursors[waPage] ?? null;
const constraints: QueryConstraint[] = [where("source", "==", "wildapricot")];
if (debouncedWaSearch.trim().length >= 2) {
const prefix = titleCase(debouncedWaSearch.trim());
constraints.push(where("name", ">=", prefix));
constraints.push(where("name", "<", prefix + ""));
}
constraints.push(orderBy("name"));
if (startCursor) constraints.push(startAfter(startCursor));
constraints.push(fsLimit(WA_PAGE_SIZE + 1)); // +1 to detect more
getDocs(query(collection(db, "events", event.id, "attendees"), ...constraints))
.then((snap) => {
if (cancelled) return;
const docs = snap.docs;
const hasMore = docs.length > WA_PAGE_SIZE;
const pageDocs = hasMore ? docs.slice(0, WA_PAGE_SIZE) : docs;
setWaRows(
pageDocs.map((d) => ({ ...(d.data() as Attendee), id: d.id }))
);
setWaHasMore(hasMore);
// Stash next-page cursor if we don't have it yet.
if (hasMore) {
const nextCursor = pageDocs[pageDocs.length - 1];
setWaCursors((prev) => {
if (prev[waPage + 1] === nextCursor) return prev;
const next = [...prev];
next[waPage + 1] = nextCursor;
return next;
});
}
})
.catch((err) => {
if (!cancelled) console.error("Failed to load WA attendees", err);
})
.finally(() => {
if (!cancelled) setWaLoading(false);
});
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [event.id, waPage, debouncedWaSearch]);
// ─── Manual attendees: small set, one-shot ─────────────────────────────
const [manualRows, setManualRows] = useState<AttendeeRow[]>([]);
const [manualLoading, setManualLoading] = useState(true);
const loadManual = useCallback(async () => {
setManualLoading(true);
try {
const snap = await getDocs(
query(
collection(db, "events", event.id, "attendees"),
where("source", "==", "app"),
orderBy("name")
)
);
setManualRows(
snap.docs.map((d) => ({ ...(d.data() as Attendee), id: d.id }))
);
} finally {
setManualLoading(false);
}
}, [event.id]);
useEffect(() => {
loadManual();
}, [loadManual]);
// Optimistic local-state mutators — avoid extra reads after admin actions.
const patchWaRow = (id: string, patch: Partial<AttendeeRow>) =>
setWaRows((rows) => rows.map((r) => (r.id === id ? { ...r, ...patch } : r)));
const patchManualRow = (id: string, patch: Partial<AttendeeRow>) =>
setManualRows((rows) =>
rows.map((r) => (r.id === id ? { ...r, ...patch } : r))
);
const computeNextHours = (row: AttendeeRow, attended: boolean): number => {
if (!attended) return 0;
if (event.eventType === "conference") return event.defaultHours ?? 0;
return (row.hours ?? 0) > 0 ? row.hours : event.defaultHours ?? 0;
};
const handleToggleAttended = async (
row: AttendeeRow,
attended: boolean
) => {
const newHours = computeNextHours(row, attended);
const patch = { attended, hours: newHours };
if (row.source === "app") patchManualRow(row.id, patch);
else patchWaRow(row.id, patch);
try {
await setAttendance({
eventId: event.id,
attendee: row,
attended,
eventType: event.eventType,
eventDefaultHours: event.defaultHours ?? 0,
user: user?.email || "",
});
} catch (err) {
console.error(err);
toast.error("Failed to update attendance");
// Roll back optimistic update.
const rollback = { attended: row.attended, hours: row.hours };
if (row.source === "app") patchManualRow(row.id, rollback);
else patchWaRow(row.id, rollback);
}
};
const handleHoursChange = async (row: AttendeeRow, newHours: number) => {
const patch = { hours: newHours };
if (row.source === "app") patchManualRow(row.id, patch);
else patchWaRow(row.id, patch);
try {
await setAttendeeHours({
eventId: event.id,
attendee: row,
newHours,
user: user?.email || "",
});
} catch (err) {
console.error(err);
toast.error("Failed to update hours");
const rollback = { hours: row.hours };
if (row.source === "app") patchManualRow(row.id, rollback);
else patchWaRow(row.id, rollback);
}
};
const handleRemoveManual = async (row: AttendeeRow) => {
if (!confirm(`Remove ${row.name} from this event?`)) return;
setManualRows((rows) => rows.filter((r) => r.id !== row.id));
try {
await removeManualAttendee({
eventId: event.id,
attendee: row,
user: user?.email || "",
});
toast.success("Attendee removed");
} catch (err) {
console.error(err);
toast.error("Failed to remove attendee");
// Re-fetch manual rows to recover state.
await loadManual();
}
};
// Columns shared between WA and manual sections.
const attendanceColumn: ColumnDef<AttendeeRow, unknown> = useMemo(
() => ({
id: "attended",
header: "Attended",
size: 100,
enableSorting: true,
accessorFn: (row) => (row.attended ? 1 : 0),
cell: ({ row }) =>
isAdmin ? (
<Switch
checked={row.original.attended}
onCheckedChange={(v) => handleToggleAttended(row.original, v)}
aria-label="Mark attended"
/>
) : row.original.attended ? (
<Badge
variant="outline"
className="text-xs text-green-700 border-green-200 bg-green-50 dark:bg-green-950/30"
>
Yes
</Badge>
) : (
<span className="text-xs text-muted-foreground">—</span>
),
}),
[isAdmin, event.eventType, event.defaultHours, user?.email]
// eslint-disable-next-line react-hooks/exhaustive-deps
);
const hoursColumn: ColumnDef<AttendeeRow, unknown> = useMemo(
() => ({
id: "hours",
header: "Hours",
size: 110,
enableSorting: true,
accessorFn: (row) => row.hours ?? 0,
cell: ({ row }) => {
const r = row.original;
if (event.eventType === "conference") {
return (
<span className="tabular-nums text-sm">
{r.attended ? r.hours : "—"}
</span>
);
}
if (!r.attended) {
return <span className="text-sm text-muted-foreground">—</span>;
}
if (!isAdmin) {
return <span className="tabular-nums text-sm">{r.hours}</span>;
}
return (
<Input
type="number"
min={0}
step="0.5"
defaultValue={r.hours}
className="h-8 w-20 text-sm"
onBlur={(e) => {
const v = Number(e.target.value);
if (Number.isFinite(v) && v !== r.hours) {
handleHoursChange(r, v);
}
}}
/>
);
},
}),
[isAdmin, event.eventType, user?.email]
// eslint-disable-next-line react-hooks/exhaustive-deps
);
const waColumns: ColumnDef<AttendeeRow, unknown>[] = useMemo(
() => [
{
accessorKey: "name",
header: "Name",
size: 200,
enableSorting: true,
cell: ({ row }) => (
<a
href={`https://mypnaa.org/admin/contacts/details/?contactId=${row.original.contactId}`}
target="_blank"
rel="noopener noreferrer"
className="font-medium text-sm text-primary hover:underline"
>
{row.original.name || "—"}
</a>
),
},
{
accessorKey: "registrationType",
header: "Registration Type",
size: 90,
enableSorting: true,
cell: ({ row }) => (
<span className="tabular-nums text-sm">
{row.original.registrationType || "—"}
</span>
),
},
{
accessorKey: "Status",
header: "Payment",
size: 100,
enableSorting: true,
filterFn: (row, _columnId, filterValue) => {
if (filterValue === "true") return row.original.isPaid;
if (filterValue === "false") return !row.original.isPaid;
return true;
},
meta: {
filterType: "select",
filterOptions: [
{ label: "Yes", value: "true" },
{ label: "No", value: "false" },
],
} satisfies ColumnMeta,
accessorFn: (row) => {
if (row.registrationFee === 0) return 1_000_000;
if (row.isPaid) return -row.paidSum;
return 2_000_000;
},
cell: ({ row }) =>
row.original.registrationFee === 0 ? (
<Badge
variant="outline"
className="text-xs text-muted-foreground border-muted bg-muted/50"
>
Free
</Badge>
) : row.original.isPaid ? (
<Badge
variant="outline"
className="text-xs text-green-700 border-green-200 bg-green-50 dark:bg-green-950/30"
>
{isNationalAdmin
? `Paid in Full - $${row.original.paidSum.toFixed(2)}`
: "Paid in Full"}
</Badge>
) : (
<Badge
variant="outline"
className="text-xs text-amber-700 border-amber-200 bg-amber-50 dark:bg-amber-950/30"
>
{isNationalAdmin
? `$${(row.original.registrationFee - row.original.paidSum).toFixed(2)} Due`
: "Unpaid"}
</Badge>
),
},
attendanceColumn,
hoursColumn,
],
[isNationalAdmin, attendanceColumn, hoursColumn]
);
const manualColumns: ColumnDef<AttendeeRow, unknown>[] = useMemo(
() => [
{
accessorKey: "name",
header: "Name",
size: 220,
enableSorting: true,
meta: { filterType: "text" } satisfies ColumnMeta,
cell: ({ row }) => (
<span className="font-medium text-sm">
{row.original.name || "—"}
</span>
),
},
attendanceColumn,
hoursColumn,
...(isAdmin
? [
{
id: "actions",
header: "",
size: 60,
enableSorting: false,
cell: ({ row }: { row: { original: AttendeeRow } }) => (
<Button
variant="ghost"
size="icon"
className="h-7 w-7 text-muted-foreground hover:text-destructive"
onClick={(e) => {
e.stopPropagation();
handleRemoveManual(row.original);
}}
aria-label="Remove attendee"
>
<Trash2 className="h-4 w-4" />
</Button>
),
} as ColumnDef<AttendeeRow, unknown>,
]
: []),
],
[isAdmin, attendanceColumn, hoursColumn]
// eslint-disable-next-line react-hooks/exhaustive-deps
);
const totalRegistered = event.registrations ?? event.attendees ?? 0;
const existingMemberIds = useMemo(
() => new Set([...waRows, ...manualRows].map((r) => r.memberId).filter(Boolean)),
[waRows, manualRows]
);
const onManualAdded = (newRow: AttendeeRow) => {
setManualRows((rows) =>
[...rows, newRow].sort((a, b) => a.name.localeCompare(b.name))
);
};
return (
<div className="space-y-6">
<section className="space-y-3">
<div className="flex items-center justify-between gap-2 flex-wrap">
<h3 className="text-sm font-semibold">
Wild Apricot Registrations
<span className="ml-2 text-xs font-normal text-muted-foreground">
{totalRegistered.toLocaleString()} total
</span>
</h3>
<SearchInput
value={waSearch}
onChange={setWaSearch}
placeholder="Search by name..."
className="w-full sm:max-w-xs"
/>
</div>
<AdvancedDataTable<AttendeeRow>
columns={waColumns}
data={waRows}
loading={waLoading}
emptyTitle={
debouncedWaSearch.trim().length >= 2
? "No matching registrations"
: "No registrations"
}
emptyDescription={
debouncedWaSearch.trim().length >= 2
? "Try a different search prefix"
: "No Wild Apricot registrations for this event"
}
emptyIcon={Users}
defaultPageSize={WA_PAGE_SIZE}
exportFilename={`PNAA_${event.id}_registrations`}
/>
<WaPaginator
page={waPage}
hasMore={waHasMore}
loading={waLoading}
rowCount={waRows.length}
onPrev={() => setWaPage((p) => Math.max(0, p - 1))}
onNext={() => setWaPage((p) => p + 1)}
/>
</section>
<section className="space-y-2">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold">
Manually Added Attendees
<span className="ml-2 text-xs font-normal text-muted-foreground">
{manualRows.length}
</span>
</h3>
{isAdmin && (
<Button size="sm" onClick={() => setAddOpen(true)}>
<UserPlus className="h-4 w-4 mr-1.5" />
Add Attendee
</Button>
)}
</div>
<AdvancedDataTable<AttendeeRow>
columns={manualColumns}
data={manualRows}
loading={manualLoading}
emptyTitle="No manual attendees"
emptyDescription={
isAdmin
? "Click 'Add Attendee' to record a member who attended"
: "No additional attendees recorded"
}
emptyIcon={UserPlus}
defaultPageSize={15}
exportFilename={`PNAA_${event.id}_manual_attendees`}
/>
</section>
{isAdmin && (
<AddManualAttendeeDialog
open={addOpen}
onOpenChange={setAddOpen}
event={event}
existingMemberIds={existingMemberIds}
onAdded={onManualAdded}
/>
)}
</div>
);
}
function WaPaginator({
page,
hasMore,
loading,
rowCount,
onPrev,
onNext,
}: {
page: number;
hasMore: boolean;
loading: boolean;
rowCount: number;
onPrev: () => void;
onNext: () => void;
}) {
if (rowCount === 0 && page === 0) return null;
return (
<div className="flex items-center justify-end gap-2 text-xs text-muted-foreground">
<span className="tabular-nums">Page {page + 1}</span>
<Button
variant="outline"
size="sm"
className="h-7 px-2"
onClick={onPrev}
disabled={page === 0 || loading}
aria-label="Previous page"
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="sm"
className="h-7 px-2"
onClick={onNext}
disabled={!hasMore || loading}
aria-label="Next page"
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
);
}
// Outer dialog defers all heavy work to the body component, which only mounts
// while `open` is true. This avoids the member-search hook running on every
// event-detail page load.
function AddManualAttendeeDialog({
open,
onOpenChange,
event,
existingMemberIds,
onAdded,
}: {
open: boolean;
onOpenChange: (v: boolean) => void;
event: AppEvent & { id: string };
existingMemberIds: Set<string>;
onAdded: (row: AttendeeRow) => void;
}) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg">
{open && (
<AddManualAttendeeDialogBody
event={event}
existingMemberIds={existingMemberIds}
onAdded={onAdded}
onClose={() => onOpenChange(false)}
/>
)}
</DialogContent>
</Dialog>
);
}
function AddManualAttendeeDialogBody({
event,
existingMemberIds,
onAdded,
onClose,
}: {
event: AppEvent & { id: string };
existingMemberIds: Set<string>;
onAdded: (row: AttendeeRow) => void;
onClose: () => void;
}) {
const { user } = useAuth();
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 250);
const [scopeChapter, setScopeChapter] = useState<boolean>(
Boolean(event.chapter)
);
const [results, setResults] = useState<(Member & { id: string })[]>([]);
const [loading, setLoading] = useState(false);
const [selected, setSelected] = useState<(Member & { id: string }) | null>(
null
);
const [hours, setHours] = useState<number>(event.defaultHours ?? 0);
const [submitting, setSubmitting] = useState(false);
const trimmed = debouncedSearch.trim();
const minSearch = 2;
// Fire a server-side prefix query only once we have ≥ 2 chars. Filters to
// active members, optionally scoped to the event's chapter to keep result
// sets small. Limited to 25 hits.
useEffect(() => {
let cancelled = false;
if (trimmed.length < minSearch) {
setResults([]);
setLoading(false);
return;
}
setLoading(true);
const prefix = titleCase(trimmed);
const constraints: QueryConstraint[] = [where("activeStatus", "==", "Active")];
if (scopeChapter && event.chapter) {
constraints.push(where("chapterName", "==", event.chapter));
}
constraints.push(where("name", ">=", prefix));
constraints.push(where("name", "<", prefix + ""));
constraints.push(orderBy("name"));
constraints.push(fsLimit(25));
getDocs(query(collection(db, "members"), ...constraints))
.then((snap) => {
if (cancelled) return;
setResults(
snap.docs.map((d) => ({ ...(d.data() as Member), id: d.id }))
);
})
.catch((err) => {
if (!cancelled) console.error("Member search failed", err);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [trimmed, scopeChapter, event.chapter]);
const isConference = event.eventType === "conference";
const effectiveHours = isConference ? (event.defaultHours ?? 0) : hours;
const submit = async () => {
if (!selected) return;
setSubmitting(true);
try {
await addManualAttendee({
eventId: event.id,
member: selected,
hours: effectiveHours,
user: user?.email || "",
});
// Mirror the doc that addManualAttendee just wrote so the parent list
// updates without a re-fetch.
onAdded({
id: `app-${selected.id}`,
registrationId: `app-${selected.id}`,
eventId: event.id,
contactId: selected.id,
name: selected.name,
attended: true,
hours: effectiveHours,
source: "app",
memberId: selected.id,
registrationTypeId: "",
registrationType: "",
organization: "",
isPaid: false,
registrationFee: 0,
paidSum: 0,
OnWaitlist: false,
Status: "",
});
toast.success(`${selected.name} added`);
onClose();
} catch (err) {
const msg = err instanceof Error ? err.message : "Failed to add attendee";
toast.error(msg);
} finally {
setSubmitting(false);
}
};
return (
<>
<DialogHeader>
<DialogTitle>Add Attendee</DialogTitle>
<DialogDescription>
Search active members by name. Type at least {minSearch} letters.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<SearchInput
value={search}
onChange={setSearch}
placeholder={`Search by name (≥ ${minSearch} chars)…`}
className="w-full"
/>
{event.chapter && (
<label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
<input
type="checkbox"
checked={scopeChapter}
onChange={(e) => setScopeChapter(e.target.checked)}
className="rounded border-input"
/>
Limit to {event.chapter}
</label>
)}
{selected ? (
<div className="rounded-md border p-3 flex items-center justify-between bg-muted/40">
<div>
<p className="font-medium text-sm">{selected.name}</p>
<p className="text-xs text-muted-foreground">
{selected.email} · {selected.chapterName || "No chapter"}
</p>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => setSelected(null)}
>
Change
</Button>
</div>
) : trimmed.length < minSearch ? (
<p className="text-sm text-muted-foreground">
Type at least {minSearch} letters to search.
</p>
) : (
<ScrollArea className="h-64 rounded-md border">
{loading ? (
<p className="text-sm text-muted-foreground p-3">Loading…</p>
) : results.length === 0 ? (
<p className="text-sm text-muted-foreground p-3">
No active members match.
</p>
) : (
<ul className="divide-y">
{results.map((m) => {
const alreadyAdded = existingMemberIds.has(m.id);
return (
<li key={m.id}>
<button
type="button"
disabled={alreadyAdded}
onClick={() => setSelected(m)}
className="w-full text-left p-3 hover:bg-muted/50 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-between"
>
<div>
<p className="font-medium text-sm">{m.name}</p>
<p className="text-xs text-muted-foreground">
{m.email} · {m.chapterName || "No chapter"}
</p>
</div>
{alreadyAdded && (
<span className="text-xs text-muted-foreground">
already added
</span>
)}
</button>
</li>
);
})}
</ul>
)}
</ScrollArea>
)}
{selected && (
<div className="space-y-1">
<label className="text-sm font-medium">Hours</label>
{isConference ? (
<p className="text-sm text-muted-foreground">
Conferences use the event's default hours:{" "}
<span className="font-medium text-foreground">
{event.defaultHours ?? 0}
</span>
</p>
) : (
<Input
type="number"
min={0}
step="0.5"
value={hours}
onChange={(e) => setHours(Number(e.target.value) || 0)}
/>
)}
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
Cancel
</Button>
<Button onClick={submit} disabled={!selected || submitting}>
{submitting ? "Adding…" : "Add Attendee"}
</Button>
</DialogFooter>
</>
);
}