<script lang="ts">
	import { enhance } from '$app/forms';
	import { invalidateAll } from '$app/navigation';
	import {
		ArrowLeft,
		Search,
		Check,
		X,
		UserPlus,
		Users,
		MapPin,
		Calendar,
		Clock,
		RefreshCw
	} from 'lucide-svelte';

	let { data, form } = $props();

	const event = $derived(data.event);
	const memberRsvps = $derived(data.memberRsvps);
	const publicRsvps = $derived(data.publicRsvps);
	const stats = $derived(data.stats);
	const availableMembers = $derived(data.availableMembers || []);

	// Local state
	let searchQuery = $state('');
	let filter = $state<'all' | 'confirmed' | 'checked' | 'unchecked'>('all');
	let showWalkInModal = $state(false);
	let walkInTab = $state<'member' | 'guest'>('member');
	let walkInMemberSearch = $state('');
	let selectedWalkInMember = $state<string | null>(null);
	let guestName = $state('');
	let guestEmail = $state('');
	let walkInLoading = $state(false);

	// Combine and filter RSVPs
	const allRsvps = $derived([
		...memberRsvps.map((r: any) => ({ ...r, type: 'member' })),
		...publicRsvps.map((r: any) => ({ ...r, type: 'public' }))
	]);

	const filteredRsvps = $derived(() => {
		let result = allRsvps;

		// Apply status filter
		if (filter === 'confirmed') {
			result = result.filter(r => r.status === 'confirmed');
		} else if (filter === 'checked') {
			result = result.filter(r => r.attended);
		} else if (filter === 'unchecked') {
			result = result.filter(r => !r.attended && r.status === 'confirmed');
		}

		// Apply search
		if (searchQuery.trim()) {
			const query = searchQuery.toLowerCase();
			result = result.filter(r => {
				if (r.type === 'member') {
					const name = `${r.member?.first_name} ${r.member?.last_name}`.toLowerCase();
					const memberId = r.member?.member_id?.toLowerCase() || '';
					return name.includes(query) || memberId.includes(query);
				} else {
					return r.full_name?.toLowerCase().includes(query);
				}
			});
		}

		// Sort: unchecked first, then checked
		return result.sort((a, b) => {
			if (a.attended && !b.attended) return 1;
			if (!a.attended && b.attended) return -1;
			return 0;
		});
	});

	// Filter available members for walk-in
	const filteredWalkInMembers = $derived(
		walkInMemberSearch.trim()
			? availableMembers.filter((m: any) => {
					const query = walkInMemberSearch.toLowerCase();
					const name = `${m.first_name} ${m.last_name}`.toLowerCase();
					return name.includes(query) || m.member_id?.toLowerCase().includes(query);
				})
			: availableMembers.slice(0, 20)
	);

	function getInitials(firstName: string, lastName: string): string {
		return `${firstName?.charAt(0) || ''}${lastName?.charAt(0) || ''}`.toUpperCase();
	}

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

	function closeWalkInModal() {
		showWalkInModal = false;
		walkInTab = 'member';
		walkInMemberSearch = '';
		selectedWalkInMember = null;
		guestName = '';
		guestEmail = '';
	}

	function handleRefresh() {
		invalidateAll();
	}
</script>

<svelte:head>
	<title>Roll Call: {event?.title || 'Event'} | Monaco USA</title>
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</svelte:head>

<div class="flex min-h-screen flex-col bg-slate-50">
	<!-- Header - Sticky -->
	<header class="sticky top-0 z-20 bg-white shadow-sm">
		<div class="px-4 py-3">
			<div class="flex items-center justify-between">
				<a
					href="/board/events/{event?.id}/attendees"
					class="flex items-center gap-2 text-slate-600 active:text-monaco-600"
				>
					<ArrowLeft class="h-5 w-5" />
					<span class="sr-only sm:not-sr-only">Back</span>
				</a>
				<div class="text-center">
					<h1 class="text-lg font-bold text-slate-900 truncate max-w-[200px] sm:max-w-none">
						{event?.title || 'Roll Call'}
					</h1>
					<div class="flex items-center justify-center gap-2 text-xs text-slate-500">
						{#if event?.start_datetime}
							<span>{formatEventDate(event.start_datetime)}</span>
						{/if}
						{#if event?.location}
							<span>• {event.location}</span>
						{/if}
					</div>
				</div>
				<button
					onclick={handleRefresh}
					class="rounded-full p-2 text-slate-500 active:bg-slate-100"
					aria-label="Refresh"
				>
					<RefreshCw class="h-5 w-5" />
				</button>
			</div>
		</div>

		<!-- Stats Bar -->
		<div class="flex items-center justify-center gap-6 border-t border-slate-100 bg-slate-50 px-4 py-2">
			<div class="text-center">
				<p class="text-2xl font-bold text-monaco-600">{stats.checkedIn}</p>
				<p class="text-xs text-slate-500">Checked In</p>
			</div>
			<div class="h-8 w-px bg-slate-200"></div>
			<div class="text-center">
				<p class="text-2xl font-bold text-slate-700">{stats.confirmed}</p>
				<p class="text-xs text-slate-500">Confirmed</p>
			</div>
			{#if stats.waitlist > 0}
				<div class="h-8 w-px bg-slate-200"></div>
				<div class="text-center">
					<p class="text-2xl font-bold text-amber-600">{stats.waitlist}</p>
					<p class="text-xs text-slate-500">Waitlist</p>
				</div>
			{/if}
		</div>

		<!-- Search Bar - Sticky -->
		<div class="border-t border-slate-100 bg-white px-4 py-3">
			<div class="relative">
				<Search class="absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
				<input
					type="text"
					bind:value={searchQuery}
					placeholder="Search attendees..."
					class="h-12 w-full rounded-xl border border-slate-200 bg-slate-50 pl-11 pr-4 text-base placeholder:text-slate-400 focus:border-monaco-500 focus:bg-white focus:outline-none focus:ring-2 focus:ring-monaco-500/20"
				/>
				{#if searchQuery}
					<button
						onclick={() => searchQuery = ''}
						class="absolute right-3 top-1/2 -translate-y-1/2 rounded-full p-1 text-slate-400 hover:bg-slate-200 hover:text-slate-600"
					>
						<X class="h-4 w-4" />
					</button>
				{/if}
			</div>
		</div>

		<!-- Filter Tabs -->
		<div class="flex gap-2 overflow-x-auto border-t border-slate-100 bg-white px-4 py-2 scrollbar-none">
			{#each [
				{ value: 'all', label: 'All', count: stats.total },
				{ value: 'confirmed', label: 'Confirmed', count: stats.confirmed },
				{ value: 'checked', label: 'Here', count: stats.checkedIn },
				{ value: 'unchecked', label: 'Not Here', count: stats.confirmed - stats.checkedIn }
			] as tab}
				<button
					onclick={() => filter = tab.value as typeof filter}
					class="flex shrink-0 items-center gap-1.5 rounded-full px-4 py-2 text-sm font-medium transition-all
					{filter === tab.value
						? 'bg-monaco-600 text-white shadow-sm'
						: 'bg-slate-100 text-slate-600 active:bg-slate-200'}"
				>
					{tab.label}
					<span class="rounded-full px-1.5 py-0.5 text-xs {filter === tab.value ? 'bg-white/20' : 'bg-slate-200'}">
						{tab.count}
					</span>
				</button>
			{/each}
		</div>
	</header>

	<!-- Attendee List -->
	<main class="flex-1 overflow-y-auto px-4 py-3 pb-24">
		{#if form?.error}
			<div class="mb-4 rounded-lg bg-red-50 p-3 text-sm text-red-600">
				{form.error}
			</div>
		{/if}

		{#if filteredRsvps().length === 0}
			<div class="flex flex-col items-center justify-center py-12 text-center">
				<Users class="h-12 w-12 text-slate-300" />
				<p class="mt-3 text-slate-600">
					{searchQuery ? 'No attendees match your search' : 'No attendees to show'}
				</p>
			</div>
		{:else}
			<div class="space-y-2">
				{#each filteredRsvps() as rsvp (rsvp.id)}
					{@const isMember = rsvp.type === 'member'}
					{@const name = isMember ? `${rsvp.member?.first_name} ${rsvp.member?.last_name}` : rsvp.full_name}
					{@const memberId = isMember ? rsvp.member?.member_id : null}
					{@const avatarUrl = isMember ? rsvp.member?.avatar_url : null}

					<form
						method="POST"
						action="?/checkIn"
						use:enhance={() => {
							return async ({ update }) => {
								await invalidateAll();
								await update({ reset: false });
							};
						}}
					>
						<input type="hidden" name="rsvp_id" value={rsvp.id} />
						<input type="hidden" name="is_public" value={!isMember} />
						<input type="hidden" name="attended" value={!rsvp.attended} />

						<button
							type="submit"
							class="flex w-full items-center gap-4 rounded-xl border bg-white p-4 transition-all active:scale-[0.98]
							{rsvp.attended
								? 'border-green-200 bg-green-50'
								: 'border-slate-200 hover:border-slate-300'}"
						>
							<!-- Avatar -->
							<div class="relative shrink-0">
								{#if avatarUrl}
									<img
										src={avatarUrl}
										alt={name}
										class="h-12 w-12 rounded-full object-cover"
									/>
								{:else}
									<div class="flex h-12 w-12 items-center justify-center rounded-full bg-slate-100 text-lg font-medium text-slate-600">
										{getInitials(isMember ? rsvp.member?.first_name : rsvp.full_name?.split(' ')[0] || '', isMember ? rsvp.member?.last_name : rsvp.full_name?.split(' ')[1] || '')}
									</div>
								{/if}
								{#if rsvp.status === 'waitlist'}
									<div class="absolute -bottom-1 -right-1 rounded-full bg-amber-400 px-1.5 py-0.5 text-[10px] font-bold text-white">
										WL
									</div>
								{/if}
							</div>

							<!-- Info -->
							<div class="min-w-0 flex-1 text-left">
								<div class="flex items-center gap-2">
									<p class="truncate font-medium text-slate-900">{name}</p>
									{#if !isMember}
										<span class="shrink-0 rounded-full bg-orange-100 px-2 py-0.5 text-xs font-medium text-orange-700">
											Guest
										</span>
									{/if}
								</div>
								{#if memberId}
									<p class="text-sm text-slate-500">{memberId}</p>
								{:else if !isMember && rsvp.email}
									<p class="truncate text-sm text-slate-500">{rsvp.email}</p>
								{/if}
								{#if rsvp.guest_count > 0}
									<p class="text-xs text-slate-400">+{rsvp.guest_count} guest{rsvp.guest_count > 1 ? 's' : ''}</p>
								{/if}
							</div>

							<!-- Check-in Button -->
							<div
								class="flex h-14 w-14 shrink-0 items-center justify-center rounded-xl text-lg font-bold transition-all
								{rsvp.attended
									? 'bg-green-500 text-white shadow-sm'
									: 'border-2 border-dashed border-slate-300 text-slate-400'}"
							>
								{#if rsvp.attended}
									<Check class="h-7 w-7" strokeWidth={3} />
								{:else}
									<span class="text-2xl">+</span>
								{/if}
							</div>
						</button>
					</form>
				{/each}
			</div>
		{/if}
	</main>

	<!-- Floating Action Button - Walk-in -->
	<button
		onclick={() => showWalkInModal = true}
		class="fixed bottom-24 right-4 z-10 flex h-14 items-center gap-2 rounded-full bg-monaco-600 px-5 text-white shadow-lg active:bg-monaco-700 lg:bottom-6"
	>
		<UserPlus class="h-5 w-5" />
		<span class="font-medium">Walk-in</span>
	</button>
</div>

<!-- Walk-in Modal -->
{#if showWalkInModal}
	<div class="fixed inset-0 z-50 flex items-end justify-center bg-black/50 sm:items-center sm:p-4">
		<div class="w-full max-w-md rounded-t-2xl bg-white sm:rounded-2xl" style="max-height: 90vh;">
			<!-- Modal Header -->
			<div class="flex items-center justify-between border-b border-slate-100 px-4 py-4">
				<h2 class="text-lg font-semibold text-slate-900">Add Walk-in</h2>
				<button
					onclick={closeWalkInModal}
					class="rounded-full p-2 text-slate-400 hover:bg-slate-100"
				>
					<X class="h-5 w-5" />
				</button>
			</div>

			<!-- Tabs -->
			<div class="flex border-b border-slate-100">
				<button
					onclick={() => walkInTab = 'member'}
					class="flex-1 border-b-2 px-4 py-3 text-sm font-medium transition-colors
					{walkInTab === 'member'
						? 'border-monaco-600 text-monaco-600'
						: 'border-transparent text-slate-500 hover:text-slate-700'}"
				>
					Existing Member
				</button>
				<button
					onclick={() => walkInTab = 'guest'}
					class="flex-1 border-b-2 px-4 py-3 text-sm font-medium transition-colors
					{walkInTab === 'guest'
						? 'border-monaco-600 text-monaco-600'
						: 'border-transparent text-slate-500 hover:text-slate-700'}"
				>
					New Guest
				</button>
			</div>

			<!-- Modal Content -->
			<div class="overflow-y-auto p-4" style="max-height: calc(90vh - 140px);">
				{#if walkInTab === 'member'}
					<!-- Member 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"
							bind:value={walkInMemberSearch}
							placeholder="Search members..."
							class="h-11 w-full rounded-lg border border-slate-200 pl-10 pr-4 text-sm focus:border-monaco-500 focus:outline-none focus:ring-1 focus:ring-monaco-500"
						/>
					</div>

					{#if filteredWalkInMembers.length === 0}
						<p class="py-8 text-center text-sm text-slate-500">
							{walkInMemberSearch ? 'No members found' : 'All members have already RSVPed'}
						</p>
					{:else}
						<div class="space-y-2">
							{#each filteredWalkInMembers as member (member.id)}
								<button
									type="button"
									onclick={() => selectedWalkInMember = selectedWalkInMember === member.id ? null : member.id}
									class="flex w-full items-center gap-3 rounded-lg border p-3 text-left transition-colors
									{selectedWalkInMember === member.id
										? 'border-monaco-500 bg-monaco-50'
										: 'border-slate-200 hover:bg-slate-50'}"
								>
									{#if member.avatar_url}
										<img src={member.avatar_url} alt="" class="h-10 w-10 rounded-full object-cover" />
									{:else}
										<div class="flex h-10 w-10 items-center justify-center rounded-full bg-slate-100 text-sm font-medium text-slate-600">
											{getInitials(member.first_name, member.last_name)}
										</div>
									{/if}
									<div class="min-w-0 flex-1">
										<p class="font-medium text-slate-900">{member.first_name} {member.last_name}</p>
										<p class="text-xs text-slate-500">{member.member_id}</p>
									</div>
									{#if selectedWalkInMember === member.id}
										<Check class="h-5 w-5 text-monaco-600" />
									{/if}
								</button>
							{/each}
						</div>
					{/if}

					<!-- Add Member Button -->
					{#if selectedWalkInMember}
						<form
							method="POST"
							action="?/addWalkIn"
							use:enhance={() => {
								walkInLoading = true;
								return async ({ update, result }) => {
									walkInLoading = false;
									if (result.type === 'success') {
										closeWalkInModal();
										await invalidateAll();
									}
									await update({ reset: false });
								};
							}}
							class="mt-4"
						>
							<input type="hidden" name="member_id" value={selectedWalkInMember} />
							<button
								type="submit"
								disabled={walkInLoading}
								class="w-full rounded-lg bg-monaco-600 py-3 font-medium text-white active:bg-monaco-700 disabled:opacity-50"
							>
								{walkInLoading ? 'Adding...' : 'Add & Check In'}
							</button>
						</form>
					{/if}
				{:else}
					<!-- Guest Form -->
					<form
						method="POST"
						action="?/addWalkIn"
						use:enhance={() => {
							walkInLoading = true;
							return async ({ update, result }) => {
								walkInLoading = false;
								if (result.type === 'success') {
									closeWalkInModal();
									await invalidateAll();
								}
								await update({ reset: false });
							};
						}}
						class="space-y-4"
					>
						<div>
							<label for="guest_name" class="mb-1 block text-sm font-medium text-slate-700">
								Guest Name <span class="text-monaco-600">*</span>
							</label>
							<input
								type="text"
								id="guest_name"
								name="guest_name"
								bind:value={guestName}
								required
								placeholder="Full name"
								class="h-11 w-full rounded-lg border border-slate-200 px-4 text-sm focus:border-monaco-500 focus:outline-none focus:ring-1 focus:ring-monaco-500"
							/>
						</div>
						<div>
							<label for="guest_email" class="mb-1 block text-sm font-medium text-slate-700">
								Email <span class="text-slate-400">(optional)</span>
							</label>
							<input
								type="email"
								id="guest_email"
								name="guest_email"
								bind:value={guestEmail}
								placeholder="email@example.com"
								class="h-11 w-full rounded-lg border border-slate-200 px-4 text-sm focus:border-monaco-500 focus:outline-none focus:ring-1 focus:ring-monaco-500"
							/>
						</div>
						<button
							type="submit"
							disabled={walkInLoading || !guestName.trim()}
							class="w-full rounded-lg bg-monaco-600 py-3 font-medium text-white active:bg-monaco-700 disabled:opacity-50"
						>
							{walkInLoading ? 'Adding...' : 'Add Guest & Check In'}
						</button>
					</form>
				{/if}
			</div>
		</div>
	</div>
{/if}

<style>
	.scrollbar-none {
		-ms-overflow-style: none;
		scrollbar-width: none;
	}
	.scrollbar-none::-webkit-scrollbar {
		display: none;
	}
</style>
