<script lang="ts">
	import { enhance } from '$app/forms';
	import { invalidateAll } from '$app/navigation';
	import {
		ArrowLeft,
		Users,
		Check,
		X,
		Clock,
		UserCheck,
		UserX,
		MoreVertical,
		Calendar,
		MapPin,
		Mail,
		Phone,
		ChevronUp,
		ChevronDown,
		CreditCard,
		DollarSign,
		Loader2,
		Send,
		Search
	} from 'lucide-svelte';
	import { Button } from '$lib/components/ui/button';
	import { FormMessage, LoadingSpinner } from '$lib/components/auth';

	let { data, form } = $props();
	let event = $derived(data.event);
	let memberRsvps = $derived(data.memberRsvps);
	let publicRsvps = $derived(data.publicRsvps);
	let stats = $derived(data.stats);
	let uninvitedMembers = $derived(data.uninvitedMembers || []);

	// Calculate pending payments count
	let pendingPaymentsCount = $derived(
		memberRsvps.filter((r: any) => r.payment_status === 'pending').length +
		publicRsvps.filter((r: any) => r.payment_status === 'pending').length
	);

	let loading = $state(false);
	let statusFilter = $state('all');
	let expandedRsvp = $state<string | null>(null);

	// Invite members modal state
	let showInviteModal = $state(false);
	let inviteLoading = $state(false);
	let selectedMembers = $state<Set<string>>(new Set());
	let inviteSearchQuery = $state('');

	// Filter uninvited members based on search
	let filteredUninvitedMembers = $derived(
		uninvitedMembers.filter((m: any) => {
			if (!inviteSearchQuery) return true;
			const search = inviteSearchQuery.toLowerCase();
			return (
				m.first_name?.toLowerCase().includes(search) ||
				m.last_name?.toLowerCase().includes(search) ||
				m.email?.toLowerCase().includes(search) ||
				m.member_id?.toLowerCase().includes(search)
			);
		})
	);

	// Toggle member selection
	function toggleMemberSelection(memberId: string) {
		const newSet = new Set(selectedMembers);
		if (newSet.has(memberId)) {
			newSet.delete(memberId);
		} else {
			newSet.add(memberId);
		}
		selectedMembers = newSet;
	}

	// Select/deselect all visible members
	function toggleSelectAll() {
		if (selectedMembers.size === filteredUninvitedMembers.length) {
			selectedMembers = new Set();
		} else {
			selectedMembers = new Set(filteredUninvitedMembers.map((m: any) => m.id));
		}
	}

	// Reset invite modal
	function closeInviteModal() {
		showInviteModal = false;
		selectedMembers = new Set();
		inviteSearchQuery = '';
	}

	// Format date
	function formatDate(dateStr: string) {
		const date = new Date(dateStr);
		return date.toLocaleDateString('en-US', {
			weekday: 'short',
			month: 'short',
			day: 'numeric',
			year: 'numeric'
		});
	}

	function formatTime(dateStr: string) {
		const date = new Date(dateStr);
		return date.toLocaleTimeString('en-US', {
			hour: 'numeric',
			minute: '2-digit',
			hour12: true
		});
	}

	// Filter RSVPs based on status
	function filterRsvps(rsvps: any[], filter: string) {
		if (filter === 'all') return rsvps;
		if (filter === 'attended') return rsvps.filter(r => r.attended);
		if (filter === 'not_attended') return rsvps.filter(r => !r.attended && r.status === 'confirmed');
		if (filter === 'pending_payment') return rsvps.filter(r => r.payment_status === 'pending');
		if (filter === 'paid') return rsvps.filter(r => r.payment_status === 'paid');
		return rsvps.filter(r => r.status === filter);
	}

	// Get status badge color
	function getStatusColor(status: string) {
		switch (status) {
			case 'confirmed':
				return 'bg-green-100 text-green-700';
			case 'waitlist':
				return 'bg-yellow-100 text-yellow-700';
			case 'maybe':
				return 'bg-blue-100 text-blue-700';
			case 'declined':
			case 'cancelled':
				return 'bg-slate-100 text-slate-700';
			default:
				return 'bg-slate-100 text-slate-700';
		}
	}

	// Get payment status badge
	function getPaymentStatusBadge(paymentStatus: string, isPaidEvent: boolean) {
		if (!isPaidEvent || paymentStatus === 'not_required') return null;
		switch (paymentStatus) {
			case 'pending':
				return { color: 'bg-amber-100 text-amber-700', label: 'Payment Pending', icon: Loader2 };
			case 'paid':
				return { color: 'bg-green-100 text-green-700', label: 'Paid', icon: Check };
			default:
				return null;
		}
	}

	// Toggle row expansion
	function toggleExpand(id: string) {
		expandedRsvp = expandedRsvp === id ? null : id;
	}

	$effect(() => {
		// Reset loading when form changes
		if (form) {
			loading = false;
		}
	});
</script>

<svelte:head>
	<title>Attendees: {event?.title || 'Event'} | Monaco USA</title>
</svelte:head>

<div class="space-y-6">
	<!-- Header -->
	<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
		<div>
			<a
				href="/board/events"
				class="mb-2 inline-flex items-center gap-2 text-sm font-medium text-slate-600 hover:text-monaco-600"
			>
				<ArrowLeft class="h-4 w-4" />
				Back to events
			</a>
			<h1 class="text-2xl font-bold text-slate-900">Attendees</h1>
			{#if event}
				<p class="mt-1 text-slate-600">{event.title}</p>
			{/if}
		</div>
		<div class="flex items-center gap-2">
			<button
				onclick={() => (showInviteModal = true)}
				class="inline-flex items-center gap-2 rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700"
			>
				<Send class="h-4 w-4" />
				Invite Members
			</button>
			<a
				href={`/board/events/${event?.id}/edit`}
				class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
			>
				Edit Event
			</a>
		</div>
	</div>

	{#if form?.error}
		<FormMessage type="error" message={form.error} />
	{/if}

	{#if form?.success}
		<FormMessage type="success" message={form.success} />
	{/if}

	{#if event}
		<!-- Event Summary -->
		<div class="glass-card p-6">
			<div class="flex flex-wrap items-center gap-4 text-sm text-slate-600">
				<div class="flex items-center gap-2">
					<Calendar class="h-4 w-4 text-monaco-600" />
					<span>{formatDate(event.start_datetime)}</span>
					<span>{formatTime(event.start_datetime)} - {formatTime(event.end_datetime)}</span>
				</div>
				{#if event.location}
					<div class="flex items-center gap-2">
						<MapPin class="h-4 w-4 text-monaco-600" />
						<span>{event.location}</span>
					</div>
				{/if}
				<div class="flex items-center gap-2">
					<Users class="h-4 w-4 text-monaco-600" />
					<span>{event.total_attendees}{event.max_attendees ? ` / ${event.max_attendees}` : ''} attendees</span>
				</div>
			</div>
		</div>

		<!-- Stats Grid -->
		<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-6">
			<div class="glass-card p-4">
				<div class="flex items-center gap-3">
					<div class="rounded-lg bg-green-100 p-2">
						<UserCheck class="h-5 w-5 text-green-600" />
					</div>
					<div>
						<p class="text-2xl font-bold text-slate-900">{stats.confirmed}</p>
						<p class="text-sm text-slate-500">Confirmed</p>
					</div>
				</div>
			</div>
			{#if event?.is_paid}
				<div class="glass-card p-4">
					<div class="flex items-center gap-3">
						<div class="rounded-lg bg-amber-100 p-2">
							<CreditCard class="h-5 w-5 text-amber-600" />
						</div>
						<div>
							<p class="text-2xl font-bold text-slate-900">{pendingPaymentsCount}</p>
							<p class="text-sm text-slate-500">Pending Payment</p>
						</div>
					</div>
				</div>
			{/if}
			<div class="glass-card p-4">
				<div class="flex items-center gap-3">
					<div class="rounded-lg bg-yellow-100 p-2">
						<Clock class="h-5 w-5 text-yellow-600" />
					</div>
					<div>
						<p class="text-2xl font-bold text-slate-900">{stats.waitlist}</p>
						<p class="text-sm text-slate-500">Waitlist</p>
					</div>
				</div>
			</div>
			<div class="glass-card p-4">
				<div class="flex items-center gap-3">
					<div class="rounded-lg bg-blue-100 p-2">
						<Clock class="h-5 w-5 text-blue-600" />
					</div>
					<div>
						<p class="text-2xl font-bold text-slate-900">{stats.maybe}</p>
						<p class="text-sm text-slate-500">Maybe</p>
					</div>
				</div>
			</div>
			<div class="glass-card p-4">
				<div class="flex items-center gap-3">
					<div class="rounded-lg bg-slate-100 p-2">
						<UserX class="h-5 w-5 text-slate-600" />
					</div>
					<div>
						<p class="text-2xl font-bold text-slate-900">{stats.declined}</p>
						<p class="text-sm text-slate-500">Declined</p>
					</div>
				</div>
			</div>
			<div class="glass-card p-4">
				<div class="flex items-center gap-3">
					<div class="rounded-lg bg-monaco-100 p-2">
						<Check class="h-5 w-5 text-monaco-600" />
					</div>
					<div>
						<p class="text-2xl font-bold text-slate-900">{stats.attended}</p>
						<p class="text-sm text-slate-500">Checked In</p>
					</div>
				</div>
			</div>
		</div>

		<!-- Filter Tabs -->
		<div class="flex flex-wrap gap-2">
			{#each [
				{ value: 'all', label: 'All' },
				{ value: 'confirmed', label: 'Confirmed' },
				{ value: 'waitlist', label: 'Waitlist' },
				{ value: 'maybe', label: 'Maybe' },
				{ value: 'attended', label: 'Checked In' },
				{ value: 'not_attended', label: 'Not Checked In' },
				...(event?.is_paid ? [
					{ value: 'pending_payment', label: 'Pending Payment' },
					{ value: 'paid', label: 'Paid' }
				] : [])
			] as filter}
				<button
					onclick={() => statusFilter = filter.value}
					class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {statusFilter === filter.value
						? 'bg-monaco-600 text-white'
						: 'bg-slate-100 text-slate-700 hover:bg-slate-200'}"
				>
					{filter.label}
				</button>
			{/each}
		</div>

		<!-- Member RSVPs -->
		{#if memberRsvps.length > 0}
			<div class="glass-card overflow-hidden">
				<div class="border-b border-slate-200 bg-slate-50 px-6 py-3">
					<h2 class="font-semibold text-slate-900">Members ({stats.totalMembers})</h2>
				</div>
				<div class="divide-y divide-slate-100">
					{#each filterRsvps(memberRsvps, statusFilter) as rsvp}
						<div class="p-4">
							<div class="flex items-center justify-between gap-4">
								<div class="flex items-center gap-3 min-w-0">
									<!-- Check-in Toggle -->
									<form
										method="POST"
										action="?/checkIn"
										use:enhance={() => {
											loading = true;
											return async ({ update }) => {
												await invalidateAll();
												loading = false;
												await update();
											};
										}}
									>
										<input type="hidden" name="rsvp_id" value={rsvp.id} />
										<input type="hidden" name="is_public" value="false" />
										<input type="hidden" name="attended" value={rsvp.attended ? 'false' : 'true'} />
										<button
											type="submit"
											disabled={loading}
											class="flex h-8 w-8 items-center justify-center rounded-full transition-colors {rsvp.attended
												? 'bg-monaco-600 text-white hover:bg-monaco-700'
												: 'border-2 border-slate-300 text-slate-400 hover:border-monaco-500 hover:text-monaco-500'}"
											title={rsvp.attended ? 'Mark as not attended' : 'Mark as attended'}
										>
											{#if rsvp.attended}
												<Check class="h-4 w-4" />
											{/if}
										</button>
									</form>

									<!-- Member Info -->
									<div class="min-w-0">
										<div class="flex items-center gap-2 flex-wrap">
											<p class="font-medium text-slate-900 truncate">
												{rsvp.member?.first_name} {rsvp.member?.last_name}
											</p>
											<span class="rounded-full px-2 py-0.5 text-xs font-medium {getStatusColor(rsvp.status)}">
												{rsvp.status}
											</span>
											{#if event?.is_paid && rsvp.payment_status === 'pending'}
												<span class="inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-700">
													<Loader2 class="h-3 w-3 animate-spin" />
													Payment Pending
												</span>
											{:else if event?.is_paid && rsvp.payment_status === 'paid'}
												<span class="inline-flex items-center gap-1 rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700">
													<DollarSign class="h-3 w-3" />
													Paid
												</span>
											{/if}
										</div>
										<p class="text-sm text-slate-500">{rsvp.member?.member_id}</p>
									</div>
								</div>

								<div class="flex items-center gap-2">
									{#if rsvp.guest_count > 0}
										<span class="rounded-full bg-slate-100 px-2 py-1 text-xs font-medium text-slate-700">
											+{rsvp.guest_count} guest{rsvp.guest_count > 1 ? 's' : ''}
										</span>
									{/if}

									<!-- Quick Mark as Paid Button (visible when pending) -->
									{#if event?.is_paid && rsvp.payment_status === 'pending'}
										<form
											method="POST"
											action="?/markAsPaid"
											use:enhance={() => {
												loading = true;
												return async ({ update, result }) => {
													loading = false;
													if (result.type === 'success') {
														await invalidateAll();
													}
													await update();
												};
											}}
										>
											<input type="hidden" name="rsvp_id" value={rsvp.id} />
											<input type="hidden" name="is_public" value="false" />
											<button
												type="submit"
												disabled={loading}
												class="flex items-center gap-1 rounded-lg border border-green-300 bg-green-50 px-2 py-1 text-xs font-medium text-green-700 hover:bg-green-100 disabled:opacity-50"
												title="Mark payment as received"
											>
												<DollarSign class="h-3.5 w-3.5" />
												Mark Paid
											</button>
										</form>
									{/if}

									<!-- Expand/Collapse -->
									<button
										onclick={() => toggleExpand(rsvp.id)}
										class="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
									>
										{#if expandedRsvp === rsvp.id}
											<ChevronUp class="h-5 w-5" />
										{:else}
											<ChevronDown class="h-5 w-5" />
										{/if}
									</button>
								</div>
							</div>

							<!-- Expanded Details -->
							{#if expandedRsvp === rsvp.id}
								<div class="mt-4 ml-11 space-y-3 border-l-2 border-slate-100 pl-4">
									<div class="flex flex-wrap items-center gap-4 text-sm">
										{#if rsvp.member?.email}
											<a href={`mailto:${rsvp.member.email}`} class="flex items-center gap-1 text-slate-600 hover:text-monaco-600">
												<Mail class="h-4 w-4" />
												{rsvp.member.email}
											</a>
										{/if}
										{#if rsvp.member?.phone}
											<a href={`tel:${rsvp.member.phone}`} class="flex items-center gap-1 text-slate-600 hover:text-monaco-600">
												<Phone class="h-4 w-4" />
												{rsvp.member.phone}
											</a>
										{/if}
									</div>

									<!-- Payment Info -->
									{#if event?.is_paid && rsvp.payment_amount}
										<div class="flex items-center gap-4 text-sm">
											<span class="text-slate-600">Amount: <strong>€{rsvp.payment_amount.toFixed(2)}</strong></span>
										</div>
									{/if}

									<!-- Actions -->
									<div class="flex flex-wrap gap-2">
										{#if event?.is_paid && rsvp.payment_status === 'pending'}
											<form
												method="POST"
												action="?/markAsPaid"
												use:enhance={() => {
													loading = true;
													return async ({ update, result }) => {
														loading = false;
														if (result.type === 'success') {
															await invalidateAll();
														}
														await update();
													};
												}}
											>
												<input type="hidden" name="rsvp_id" value={rsvp.id} />
												<input type="hidden" name="is_public" value="false" />
												<Button type="submit" variant="outline" size="sm" disabled={loading} class="border-green-300 text-green-700 hover:bg-green-50">
													<DollarSign class="mr-1 h-3.5 w-3.5" />
													Mark as Paid
												</Button>
											</form>
										{/if}
										{#if rsvp.status === 'waitlist'}
											<form
												method="POST"
												action="?/promoteFromWaitlist"
												use:enhance={() => {
													loading = true;
													return async ({ update, result }) => {
														loading = false;
														if (result.type === 'success') {
															await invalidateAll();
														}
														await update();
													};
												}}
											>
												<input type="hidden" name="rsvp_id" value={rsvp.id} />
												<input type="hidden" name="is_public" value="false" />
												<Button type="submit" variant="outline" size="sm" disabled={loading}>
													<UserCheck class="mr-1 h-3.5 w-3.5" />
													Promote to Confirmed
												</Button>
											</form>
										{/if}
										<form
											method="POST"
											action="?/deleteRsvp"
											use:enhance={() => {
												if (!confirm('Remove this RSVP? This cannot be undone.')) {
													return async () => {};
												}
												loading = true;
												return async ({ update, result }) => {
													loading = false;
													if (result.type === 'success') {
														await invalidateAll();
													}
													await update();
												};
											}}
										>
											<input type="hidden" name="rsvp_id" value={rsvp.id} />
											<input type="hidden" name="is_public" value="false" />
											<Button type="submit" variant="ghost" size="sm" disabled={loading} class="text-red-600 hover:bg-red-50">
												<X class="mr-1 h-3.5 w-3.5" />
												Remove RSVP
											</Button>
										</form>
									</div>
								</div>
							{/if}
						</div>
					{/each}
				</div>
			</div>
		{/if}

		<!-- Non-Member RSVPs -->
		{#if publicRsvps.length > 0}
			<div class="glass-card overflow-hidden">
				<div class="border-b border-slate-200 bg-slate-50 px-6 py-3">
					<h2 class="font-semibold text-slate-900">Non-Members ({stats.totalNonMembers})</h2>
				</div>
				<div class="divide-y divide-slate-100">
					{#each filterRsvps(publicRsvps, statusFilter) as rsvp}
						<div class="p-4">
							<div class="flex items-center justify-between gap-4">
								<div class="flex items-center gap-3 min-w-0">
									<!-- Check-in Toggle -->
									<form
										method="POST"
										action="?/checkIn"
										use:enhance={() => {
											loading = true;
											return async ({ update }) => {
												await invalidateAll();
												loading = false;
												await update();
											};
										}}
									>
										<input type="hidden" name="rsvp_id" value={rsvp.id} />
										<input type="hidden" name="is_public" value="true" />
										<input type="hidden" name="attended" value={rsvp.attended ? 'false' : 'true'} />
										<button
											type="submit"
											disabled={loading}
											class="flex h-8 w-8 items-center justify-center rounded-full transition-colors {rsvp.attended
												? 'bg-monaco-600 text-white hover:bg-monaco-700'
												: 'border-2 border-slate-300 text-slate-400 hover:border-monaco-500 hover:text-monaco-500'}"
											title={rsvp.attended ? 'Mark as not attended' : 'Mark as attended'}
										>
											{#if rsvp.attended}
												<Check class="h-4 w-4" />
											{/if}
										</button>
									</form>

									<!-- Non-Member Info -->
									<div class="min-w-0">
										<div class="flex items-center gap-2 flex-wrap">
											<p class="font-medium text-slate-900 truncate">
												{rsvp.full_name}
											</p>
											<span class="rounded-full bg-orange-100 px-2 py-0.5 text-xs font-medium text-orange-700">
												Guest
											</span>
											<span class="rounded-full px-2 py-0.5 text-xs font-medium {getStatusColor(rsvp.status)}">
												{rsvp.status}
											</span>
											{#if event?.is_paid && rsvp.payment_status === 'pending'}
												<span class="inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-700">
													<Loader2 class="h-3 w-3 animate-spin" />
													Payment Pending
												</span>
											{:else if event?.is_paid && rsvp.payment_status === 'paid'}
												<span class="inline-flex items-center gap-1 rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700">
													<DollarSign class="h-3 w-3" />
													Paid
												</span>
											{/if}
										</div>
										<p class="text-sm text-slate-500">{rsvp.email}</p>
									</div>
								</div>

								<div class="flex items-center gap-2">
									{#if rsvp.guest_count > 0}
										<span class="rounded-full bg-slate-100 px-2 py-1 text-xs font-medium text-slate-700">
											+{rsvp.guest_count} guest{rsvp.guest_count > 1 ? 's' : ''}
										</span>
									{/if}

									<!-- Quick Mark as Paid Button (visible when pending) -->
									{#if event?.is_paid && rsvp.payment_status === 'pending'}
										<form
											method="POST"
											action="?/markAsPaid"
											use:enhance={() => {
												loading = true;
												return async ({ update, result }) => {
													loading = false;
													if (result.type === 'success') {
														await invalidateAll();
													}
													await update();
												};
											}}
										>
											<input type="hidden" name="rsvp_id" value={rsvp.id} />
											<input type="hidden" name="is_public" value="true" />
											<button
												type="submit"
												disabled={loading}
												class="flex items-center gap-1 rounded-lg border border-green-300 bg-green-50 px-2 py-1 text-xs font-medium text-green-700 hover:bg-green-100 disabled:opacity-50"
												title="Mark payment as received"
											>
												<DollarSign class="h-3.5 w-3.5" />
												Mark Paid
											</button>
										</form>
									{/if}

									<!-- Expand/Collapse -->
									<button
										onclick={() => toggleExpand(`public-${rsvp.id}`)}
										class="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
									>
										{#if expandedRsvp === `public-${rsvp.id}`}
											<ChevronUp class="h-5 w-5" />
										{:else}
											<ChevronDown class="h-5 w-5" />
										{/if}
									</button>
								</div>
							</div>

							<!-- Expanded Details -->
							{#if expandedRsvp === `public-${rsvp.id}`}
								<div class="mt-4 ml-11 space-y-3 border-l-2 border-slate-100 pl-4">
									<div class="flex flex-wrap items-center gap-4 text-sm">
										<a href={`mailto:${rsvp.email}`} class="flex items-center gap-1 text-slate-600 hover:text-monaco-600">
											<Mail class="h-4 w-4" />
											{rsvp.email}
										</a>
										{#if rsvp.phone}
											<a href={`tel:${rsvp.phone}`} class="flex items-center gap-1 text-slate-600 hover:text-monaco-600">
												<Phone class="h-4 w-4" />
												{rsvp.phone}
											</a>
										{/if}
									</div>

									<!-- Payment Info -->
									{#if event?.is_paid && rsvp.payment_amount}
										<div class="flex items-center gap-4 text-sm">
											<span class="text-slate-600">Amount: <strong>€{rsvp.payment_amount.toFixed(2)}</strong></span>
										</div>
									{/if}

									<!-- Actions -->
									<div class="flex flex-wrap gap-2">
										{#if event?.is_paid && rsvp.payment_status === 'pending'}
											<form
												method="POST"
												action="?/markAsPaid"
												use:enhance={() => {
													loading = true;
													return async ({ update, result }) => {
														loading = false;
														if (result.type === 'success') {
															await invalidateAll();
														}
														await update();
													};
												}}
											>
												<input type="hidden" name="rsvp_id" value={rsvp.id} />
												<input type="hidden" name="is_public" value="true" />
												<Button type="submit" variant="outline" size="sm" disabled={loading} class="border-green-300 text-green-700 hover:bg-green-50">
													<DollarSign class="mr-1 h-3.5 w-3.5" />
													Mark as Paid
												</Button>
											</form>
										{/if}
										{#if rsvp.status === 'waitlist'}
											<form
												method="POST"
												action="?/promoteFromWaitlist"
												use:enhance={() => {
													loading = true;
													return async ({ update, result }) => {
														loading = false;
														if (result.type === 'success') {
															await invalidateAll();
														}
														await update();
													};
												}}
											>
												<input type="hidden" name="rsvp_id" value={rsvp.id} />
												<input type="hidden" name="is_public" value="true" />
												<Button type="submit" variant="outline" size="sm" disabled={loading}>
													<UserCheck class="mr-1 h-3.5 w-3.5" />
													Promote to Confirmed
												</Button>
											</form>
										{/if}
										<form
											method="POST"
											action="?/deleteRsvp"
											use:enhance={() => {
												if (!confirm('Remove this RSVP? This cannot be undone.')) {
													return async () => {};
												}
												loading = true;
												return async ({ update, result }) => {
													loading = false;
													if (result.type === 'success') {
														await invalidateAll();
													}
													await update();
												};
											}}
										>
											<input type="hidden" name="rsvp_id" value={rsvp.id} />
											<input type="hidden" name="is_public" value="true" />
											<Button type="submit" variant="ghost" size="sm" disabled={loading} class="text-red-600 hover:bg-red-50">
												<X class="mr-1 h-3.5 w-3.5" />
												Remove RSVP
											</Button>
										</form>
									</div>
								</div>
							{/if}
						</div>
					{/each}
				</div>
			</div>
		{/if}

		<!-- Empty State -->
		{#if memberRsvps.length === 0 && publicRsvps.length === 0}
			<div class="glass-card p-12 text-center">
				<Users class="mx-auto h-12 w-12 text-slate-300" />
				<h3 class="mt-4 text-lg font-medium text-slate-900">No RSVPs yet</h3>
				<p class="mt-2 text-slate-500">No one has RSVP'd to this event yet.</p>
			</div>
		{/if}
	{:else}
		<div class="glass-card p-12 text-center">
			<p class="text-slate-600">Event not found.</p>
			<a href="/board/events" class="mt-4 inline-block text-monaco-600 hover:underline">
				View all events
			</a>
		</div>
	{/if}
</div>

<!-- Invite Members Modal -->
{#if showInviteModal}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-lg p-6">
			<div class="mb-4 flex items-center justify-between">
				<div class="flex items-center gap-3 text-monaco-600">
					<Send class="h-6 w-6" />
					<h3 class="text-lg font-semibold text-slate-900">Invite Members to Event</h3>
				</div>
				<button
					onclick={closeInviteModal}
					class="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
				>
					<X class="h-5 w-5" />
				</button>
			</div>

			<p class="mb-4 text-sm text-slate-600">
				Select members to send an email invitation with a link to RSVP for "{event?.title}".
			</p>

			<!-- Search -->
			<div class="relative mb-4">
				<Search class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
				<input
					type="text"
					placeholder="Search members..."
					bind:value={inviteSearchQuery}
					class="h-10 w-full rounded-lg border border-slate-200 bg-white pl-9 pr-4 text-sm focus:border-monaco-500 focus:outline-none focus:ring-1 focus:ring-monaco-500"
				/>
			</div>

			{#if uninvitedMembers.length === 0}
				<div class="rounded-lg bg-slate-50 p-6 text-center">
					<Users class="mx-auto h-8 w-8 text-slate-300" />
					<p class="mt-2 text-sm text-slate-600">All members have already been invited or RSVPed.</p>
				</div>
			{:else}
				<!-- Select All -->
				<div class="mb-2 flex items-center justify-between text-sm">
					<button
						onclick={toggleSelectAll}
						class="font-medium text-monaco-600 hover:text-monaco-700"
					>
						{selectedMembers.size === filteredUninvitedMembers.length ? 'Deselect All' : 'Select All'}
					</button>
					<span class="text-slate-500">
						{selectedMembers.size} of {filteredUninvitedMembers.length} selected
					</span>
				</div>

				<!-- Member List -->
				<div class="max-h-64 overflow-y-auto rounded-lg border border-slate-200">
					{#each filteredUninvitedMembers as member (member.id)}
						<label
							class="flex cursor-pointer items-center gap-3 border-b border-slate-100 px-4 py-3 hover:bg-slate-50 last:border-b-0"
						>
							<input
								type="checkbox"
								checked={selectedMembers.has(member.id)}
								onchange={() => toggleMemberSelection(member.id)}
								class="h-4 w-4 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
							/>
							<div class="flex-1 min-w-0">
								<p class="font-medium text-slate-900 truncate">
									{member.first_name} {member.last_name}
								</p>
								<p class="text-xs text-slate-500 truncate">{member.email}</p>
							</div>
							<span class="text-xs text-slate-400">{member.member_id}</span>
						</label>
					{:else}
						<div class="p-4 text-center text-sm text-slate-500">
							No members match your search.
						</div>
					{/each}
				</div>
			{/if}

			<!-- Actions -->
			<div class="mt-4 flex gap-3">
				<button
					onclick={closeInviteModal}
					disabled={inviteLoading}
					class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50"
				>
					Cancel
				</button>
				<form
					method="POST"
					action="?/inviteMembers"
					use:enhance={() => {
						inviteLoading = true;
						return async ({ update, result }) => {
							inviteLoading = false;
							if (result.type === 'success') {
								closeInviteModal();
								await invalidateAll();
							}
							await update();
						};
					}}
					class="flex-1"
				>
					{#each Array.from(selectedMembers) as memberId}
						<input type="hidden" name="member_ids" value={memberId} />
					{/each}
					<button
						type="submit"
						disabled={inviteLoading || selectedMembers.size === 0}
						class="w-full rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{#if inviteLoading}
							<span class="inline-flex items-center gap-2">
								<Loader2 class="h-4 w-4 animate-spin" />
								Sending...
							</span>
						{:else}
							Send {selectedMembers.size} Invitation{selectedMembers.size !== 1 ? 's' : ''}
						{/if}
					</button>
				</form>
			</div>
		</div>
	</div>
{/if}
