<script lang="ts">
	import {
		Calendar,
		Plus,
		Search,
		Clock,
		MapPin,
		Users,
		Eye,
		Edit,
		Trash2,
		X,
		FileText,
		CheckCircle2,
		XCircle,
		AlertCircle
	} from 'lucide-svelte';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { DatePicker } from '$lib/components/ui';
	import { CalendarDate, today, getLocalTimeZone } from '@internationalized/date';
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import { enhance } from '$app/forms';
	import { invalidateAll } from '$app/navigation';

	let { data, form } = $props();
	let events = $derived(data.events);
	let eventTypes = $derived(data.eventTypes);
	let stats = $derived(data.stats);
	let filters = $derived(data.filters);

	let statusFilter = $state(data.filters.status);
	let showCreateModal = $state(false);
	let isSubmitting = $state(false);
	let isPaid = $state(false);

	// Date picker state
	const todayDate = today(getLocalTimeZone());
	let startDate = $state<CalendarDate | undefined>(todayDate);
	let endDate = $state<CalendarDate | undefined>(todayDate);

	function updateFilters(newFilters: Record<string, string>) {
		const params = new URLSearchParams($page.url.searchParams);
		for (const [key, value] of Object.entries(newFilters)) {
			if (value && value !== 'all') {
				params.set(key, value);
			} else {
				params.delete(key);
			}
		}
		goto(`?${params.toString()}`, { replaceState: true });
	}

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

	// Format time
	function formatTime(dateStr: string): string {
		return new Date(dateStr).toLocaleTimeString('en-US', {
			hour: 'numeric',
			minute: '2-digit'
		});
	}

	// Get status info
	function getStatusInfo(status: string) {
		switch (status) {
			case 'published':
				return { icon: CheckCircle2, color: 'text-green-600', bg: 'bg-green-100', label: 'Published' };
			case 'draft':
				return { icon: FileText, color: 'text-slate-500', bg: 'bg-slate-100', label: 'Draft' };
			case 'cancelled':
				return { icon: XCircle, color: 'text-red-600', bg: 'bg-red-100', label: 'Cancelled' };
			case 'completed':
				return { icon: CheckCircle2, color: 'text-blue-600', bg: 'bg-blue-100', label: 'Completed' };
			default:
				return { icon: AlertCircle, color: 'text-slate-500', bg: 'bg-slate-100', label: status };
		}
	}

	// Get visibility label
	function getVisibilityLabel(visibility: string) {
		switch (visibility) {
			case 'public':
				return 'Public';
			case 'members':
				return 'Members Only';
			case 'board':
				return 'Board Only';
			case 'admin':
				return 'Admin Only';
			default:
				return visibility;
		}
	}

	// Check if event is in past
	function isPast(endDatetime: string): boolean {
		return new Date(endDatetime) < new Date();
	}

	// Default times
	const defaultTime = '18:00';
	const defaultEndTime = '20:00';

	// Reset dates when modal opens
	function openCreateModal() {
		startDate = todayDate;
		endDate = todayDate;
		isPaid = false;
		showCreateModal = true;
	}
</script>

<svelte:head>
	<title>Event Management | Monaco USA</title>
</svelte:head>

<div class="space-y-6">
	<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
		<div>
			<h1 class="text-2xl font-bold text-slate-900">Event Management</h1>
			<p class="text-slate-500">Create and manage association events</p>
		</div>

		<button
			onclick={openCreateModal}
			class="flex items-center gap-2 rounded-lg bg-monaco-600 px-4 py-2 font-medium text-white hover:bg-monaco-700"
		>
			<Plus class="h-5 w-5" />
			Create Event
		</button>
	</div>

	<!-- Stats Cards -->
	<div class="grid grid-cols-2 gap-4 sm:grid-cols-4">
		<div class="glass-card p-4">
			<div class="flex items-center gap-3">
				<div class="rounded-lg bg-slate-100 p-2">
					<Calendar class="h-5 w-5 text-slate-600" />
				</div>
				<div>
					<p class="text-2xl font-bold text-slate-900">{stats.total}</p>
					<p class="text-xs text-slate-500">Total Events</p>
				</div>
			</div>
		</div>
		<div class="glass-card p-4">
			<div class="flex items-center gap-3">
				<div class="rounded-lg bg-green-100 p-2">
					<CheckCircle2 class="h-5 w-5 text-green-600" />
				</div>
				<div>
					<p class="text-2xl font-bold text-slate-900">{stats.upcoming}</p>
					<p class="text-xs text-slate-500">Upcoming</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">
					<FileText class="h-5 w-5 text-slate-500" />
				</div>
				<div>
					<p class="text-2xl font-bold text-slate-900">{stats.draft}</p>
					<p class="text-xs text-slate-500">Drafts</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.past}</p>
					<p class="text-xs text-slate-500">Past Events</p>
				</div>
			</div>
		</div>
	</div>

	<!-- Filters -->
	<div class="flex items-center gap-4">
		<select
			bind:value={statusFilter}
			onchange={() => updateFilters({ status: statusFilter })}
			class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm"
		>
			<option value="all">All Events</option>
			<option value="published">Published</option>
			<option value="draft">Draft</option>
			<option value="cancelled">Cancelled</option>
			<option value="completed">Completed</option>
		</select>
	</div>

	{#if form?.error}
		<div class="rounded-lg bg-red-50 p-4 text-sm text-red-600">
			{form.error}
		</div>
	{/if}

	{#if form?.success}
		<div class="rounded-lg bg-green-50 p-4 text-sm text-green-600">
			{form.success}
		</div>
	{/if}

	<!-- Events List -->
	<div class="glass-card overflow-hidden">
		{#if events.length === 0}
			<div class="flex flex-col items-center justify-center p-12 text-center">
				<Calendar class="mb-4 h-16 w-16 text-slate-300" />
				<h3 class="text-lg font-medium text-slate-900">No events found</h3>
				<p class="mt-1 text-slate-500">
					{filters.status !== 'all'
						? 'Try adjusting your filters.'
						: 'Create your first event to get started.'}
				</p>
			</div>
		{:else}
			<div class="overflow-x-auto">
				<table class="w-full">
					<thead class="bg-slate-50">
						<tr>
							<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">
								Event
							</th>
							<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">
								Date & Time
							</th>
							<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">
								Attendees
							</th>
							<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">
								Visibility
							</th>
							<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">
								Status
							</th>
							<th class="px-6 py-3 text-right text-xs font-medium uppercase text-slate-500">
								Actions
							</th>
						</tr>
					</thead>
					<tbody class="divide-y divide-slate-100">
						{#each events as event}
							{@const statusInfo = getStatusInfo(event.status)}
							{@const eventPast = isPast(event.end_datetime)}
							<tr
								class="hover:bg-slate-50 cursor-pointer {eventPast ? 'opacity-60' : ''}"
								onclick={(e) => {
									// Don't navigate if clicking on action buttons
									if ((e.target as HTMLElement).closest('.actions-cell')) return;
									goto(`/events/${event.id}`);
								}}
								onkeydown={(e) => {
									if (e.key === 'Enter' || e.key === ' ') {
										e.preventDefault();
										goto(`/events/${event.id}`);
									}
								}}
								tabindex="0"
								role="button"
							>
								<td class="px-6 py-4">
									<div>
										<p class="font-medium text-slate-900">{event.title}</p>
										{#if event.event_type_name}
											<span
												class="inline-block mt-1 rounded-full px-2 py-0.5 text-xs font-medium"
												style="background-color: {event.event_type_color}20; color: {event.event_type_color}"
											>
												{event.event_type_name}
											</span>
										{/if}
									</div>
								</td>
								<td class="px-6 py-4">
									<div class="text-sm">
										<p class="text-slate-900">{formatDate(event.start_datetime)}</p>
										<p class="text-slate-500">
											{formatTime(event.start_datetime)} - {formatTime(event.end_datetime)}
										</p>
									</div>
								</td>
								<td class="px-6 py-4">
									<div class="flex items-center gap-1.5 text-sm text-slate-600">
										<Users class="h-4 w-4" />
										{event.total_attendees || 0}
										{#if event.max_attendees}
											/ {event.max_attendees}
										{/if}
									</div>
									{#if event.waitlist_count > 0}
										<p class="text-xs text-yellow-600">{event.waitlist_count} on waitlist</p>
									{/if}
								</td>
								<td class="px-6 py-4">
									<span class="text-sm text-slate-600">
										{getVisibilityLabel(event.visibility)}
									</span>
								</td>
								<td class="px-6 py-4">
									<span
										class="inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-medium {statusInfo.bg} {statusInfo.color}"
									>
										<svelte:component this={statusInfo.icon} class="h-3.5 w-3.5" />
										{statusInfo.label}
									</span>
								</td>
								<td class="actions-cell px-6 py-4 text-right" onclick={(e) => e.stopPropagation()}>
									<div class="flex justify-end gap-2">
										<a
											href="/events/{event.id}"
											class="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
											title="View"
										>
											<Eye class="h-4 w-4" />
										</a>
										<a
											href="/board/events/{event.id}/attendees"
											class="rounded p-1.5 text-slate-400 hover:bg-monaco-100 hover:text-monaco-600"
											title="Manage Attendees"
										>
											<Users class="h-4 w-4" />
										</a>
										<a
											href="/board/events/{event.id}/edit"
											class="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
											title="Edit"
										>
											<Edit class="h-4 w-4" />
										</a>
										{#if event.status === 'draft'}
											<form method="POST" action="?/updateStatus" class="inline">
												<input type="hidden" name="event_id" value={event.id} />
												<input type="hidden" name="status" value="published" />
												<button
													type="submit"
													class="rounded p-1.5 text-slate-400 hover:bg-green-100 hover:text-green-600"
													title="Publish"
												>
													<CheckCircle2 class="h-4 w-4" />
												</button>
											</form>
										{/if}
									</div>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
		{/if}
	</div>
</div>

<!-- Create Event Modal -->
{#if showCreateModal}
	<div class="fixed inset-0 z-50 overflow-y-auto bg-black/50">
		<div class="flex min-h-full items-start justify-center p-4 sm:items-center sm:p-6">
			<div class="w-full max-w-2xl rounded-2xl bg-white p-6 shadow-xl">
				<div class="mb-6 flex items-center justify-between">
					<h2 class="text-lg font-semibold text-slate-900">Create New Event</h2>
					<button onclick={() => (showCreateModal = false)} class="rounded p-1 hover:bg-slate-100">
						<X class="h-5 w-5 text-slate-500" />
					</button>
				</div>

				<form
				method="POST"
				action="?/create"
				use:enhance={() => {
					isSubmitting = true;
					return async ({ update, result }) => {
						isSubmitting = false;
						if (result.type === 'success') {
							showCreateModal = false;
							await invalidateAll();
						}
						await update();
					};
				}}
				class="space-y-4"
			>
				<div class="grid gap-4 sm:grid-cols-2">
					<div class="sm:col-span-2">
						<Label for="title">Event Title *</Label>
						<Input type="text" id="title" name="title" required class="mt-1" />
					</div>

					<div class="sm:col-span-2">
						<Label for="description">Description</Label>
						<textarea
							id="description"
							name="description"
							rows="3"
							class="mt-1 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
						></textarea>
					</div>

					<div>
						<Label for="event_type_id">Event Type</Label>
						<select
							id="event_type_id"
							name="event_type_id"
							class="mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm"
						>
							<option value="">Select type...</option>
							{#each eventTypes as type}
								<option value={type.id}>{type.display_name}</option>
							{/each}
						</select>
					</div>

					<div>
						<Label for="location">Location</Label>
						<Input type="text" id="location" name="location" class="mt-1" />
					</div>

					<div>
						<Label>Start Date *</Label>
						<div class="mt-1">
							<DatePicker
								bind:value={startDate}
								placeholder="Select start date"
								name="start_date"
							/>
						</div>
					</div>

					<div>
						<Label for="start_time">Start Time *</Label>
						<Input type="time" id="start_time" name="start_time" value={defaultTime} required class="mt-1" />
					</div>

					<div>
						<Label>End Date *</Label>
						<div class="mt-1">
							<DatePicker
								bind:value={endDate}
								minValue={startDate}
								placeholder="Select end date"
								name="end_date"
							/>
						</div>
					</div>

					<div>
						<Label for="end_time">End Time *</Label>
						<Input type="time" id="end_time" name="end_time" value={defaultEndTime} required class="mt-1" />
					</div>

					<div>
						<Label for="max_attendees">Max Attendees</Label>
						<Input
							type="number"
							id="max_attendees"
							name="max_attendees"
							placeholder="Unlimited"
							class="mt-1"
						/>
					</div>

					<div>
						<Label for="max_guests_per_member">Max Guests per Member</Label>
						<Input
							type="number"
							id="max_guests_per_member"
							name="max_guests_per_member"
							value="1"
							min="0"
							class="mt-1"
						/>
					</div>

					<div class="sm:col-span-2">
						<label class="flex items-center gap-2">
							<input
								type="checkbox"
								name="is_paid"
								value="true"
								bind:checked={isPaid}
								class="rounded border-slate-300"
							/>
							<span class="text-sm font-medium text-slate-700">This is a paid event</span>
						</label>
					</div>

					{#if isPaid}
						<div>
							<Label for="member_price">Member Price (€)</Label>
							<Input
								type="number"
								id="member_price"
								name="member_price"
								step="0.01"
								value="0"
								class="mt-1"
							/>
						</div>

						<div>
							<Label for="non_member_price">Non-Member Price (€)</Label>
							<Input
								type="number"
								id="non_member_price"
								name="non_member_price"
								step="0.01"
								value="0"
								class="mt-1"
							/>
						</div>
					{/if}

					<div>
						<Label for="visibility">Visibility</Label>
						<select
							id="visibility"
							name="visibility"
							class="mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm"
						>
							<option value="members">Members Only</option>
							<option value="public">Public</option>
							<option value="board">Board Only</option>
							<option value="admin">Admin Only</option>
						</select>
					</div>

					<div>
						<Label for="status">Status</Label>
						<select
							id="status"
							name="status"
							class="mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm"
						>
							<option value="published">Published</option>
							<option value="draft">Draft</option>
						</select>
					</div>
				</div>

				<div class="flex gap-3 pt-4">
					<button
						type="button"
						onclick={() => (showCreateModal = false)}
						class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
					>
						Cancel
					</button>
					<button
						type="submit"
						disabled={isSubmitting}
						class="flex flex-1 items-center justify-center gap-2 rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{#if isSubmitting}
							<div class="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"
							></div>
							Creating...
						{:else}
							<Plus class="h-4 w-4" />
							Create Event
						{/if}
					</button>
				</div>
			</form>
			</div>
		</div>
	</div>
{/if}
