<script lang="ts">
	import { ArrowLeft, Save, Trash2, Calendar, MapPin, Users, DollarSign, Eye, X } 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 } from '@internationalized/date';
	import { enhance } from '$app/forms';
	import { goto, invalidateAll } from '$app/navigation';

	let { data, form } = $props();
	const { event, eventTypes, member } = data;

	let isSubmitting = $state(false);
	let showDeleteConfirm = $state(false);

	// Parse existing dates into CalendarDate
	const startDateJS = event.start_datetime ? new Date(event.start_datetime) : new Date();
	const endDateJS = event.end_datetime ? new Date(event.end_datetime) : new Date();

	let startDate = $state<CalendarDate | undefined>(
		new CalendarDate(startDateJS.getFullYear(), startDateJS.getMonth() + 1, startDateJS.getDate())
	);
	let endDate = $state<CalendarDate | undefined>(
		new CalendarDate(endDateJS.getFullYear(), endDateJS.getMonth() + 1, endDateJS.getDate())
	);

	let isPaid = $state(event.is_paid || false);

	// Format time for input
	function formatTimeForInput(date: Date): string {
		return date.toTimeString().slice(0, 5);
	}
</script>

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

<div class="mx-auto max-w-4xl space-y-6">
	<!-- Back button -->
	<a
		href="/board/events"
		class="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>

	<div class="glass-card p-6">
		<div class="mb-6">
			<h1 class="text-2xl font-bold text-slate-900">Edit Event</h1>
			<p class="text-slate-500">Update event details and settings</p>
		</div>

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

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

		<form
			method="POST"
			action="?/update"
			use:enhance={() => {
				isSubmitting = true;
				return async ({ update }) => {
					await invalidateAll();
					await update();
					isSubmitting = false;
				};
			}}
			class="space-y-6"
		>
			<!-- Basic Info -->
			<div class="space-y-4">
				<h2 class="flex items-center gap-2 text-lg font-semibold text-slate-900">
					<Calendar class="h-5 w-5 text-monaco-600" />
					Event Details
				</h2>

				<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"
							value={event.title}
							required
							class="mt-1"
						/>
					</div>

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

					<div>
						<Label for="event_type_id">Event Type</Label>
						<select
							id="event_type_id"
							name="event_type_id"
							value={event.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="status">Status</Label>
						<select
							id="status"
							name="status"
							value={event.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>
							<option value="cancelled">Cancelled</option>
							<option value="completed">Completed</option>
						</select>
					</div>
				</div>
			</div>

			<!-- Date & Time -->
			<div class="space-y-4">
				<h2 class="text-lg font-semibold text-slate-900">Date & Time</h2>

				<div class="grid gap-4 sm:grid-cols-2">
					<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={formatTimeForInput(startDateJS)}
							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={formatTimeForInput(endDateJS)}
							required
							class="mt-1"
						/>
					</div>
				</div>
			</div>

			<!-- Location -->
			<div class="space-y-4">
				<h2 class="flex items-center gap-2 text-lg font-semibold text-slate-900">
					<MapPin class="h-5 w-5 text-monaco-600" />
					Location
				</h2>

				<div class="grid gap-4 sm:grid-cols-2">
					<div>
						<Label for="location">Location</Label>
						<Input
							type="text"
							id="location"
							name="location"
							value={event.location || ''}
							placeholder="e.g., Hotel Hermitage, Monte Carlo"
							class="mt-1"
						/>
					</div>

					<div>
						<Label for="location_url">Map Link (optional)</Label>
						<Input
							type="url"
							id="location_url"
							name="location_url"
							value={event.location_url || ''}
							placeholder="https://maps.google.com/..."
							class="mt-1"
						/>
					</div>
				</div>
			</div>

			<!-- Capacity -->
			<div class="space-y-4">
				<h2 class="flex items-center gap-2 text-lg font-semibold text-slate-900">
					<Users class="h-5 w-5 text-monaco-600" />
					Capacity
				</h2>

				<div class="grid gap-4 sm:grid-cols-2">
					<div>
						<Label for="max_attendees">Max Attendees</Label>
						<Input
							type="number"
							id="max_attendees"
							name="max_attendees"
							value={event.max_attendees || ''}
							placeholder="Unlimited"
							min="1"
							class="mt-1"
						/>
						<p class="mt-1 text-xs text-slate-500">Leave empty for unlimited</p>
					</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={event.max_guests_per_member || 1}
							min="0"
							class="mt-1"
						/>
					</div>
				</div>
			</div>

			<!-- Pricing -->
			<div class="space-y-4">
				<h2 class="flex items-center gap-2 text-lg font-semibold text-slate-900">
					<DollarSign class="h-5 w-5 text-monaco-600" />
					Pricing
				</h2>

				<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>

				{#if isPaid}
					<div class="grid gap-4 sm:grid-cols-2">
						<div>
							<Label for="member_price">Member Price (EUR)</Label>
							<Input
								type="number"
								id="member_price"
								name="member_price"
								value={event.member_price || 0}
								step="0.01"
								min="0"
								class="mt-1"
							/>
						</div>

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

			<!-- Visibility -->
			<div class="space-y-4">
				<h2 class="flex items-center gap-2 text-lg font-semibold text-slate-900">
					<Eye class="h-5 w-5 text-monaco-600" />
					Visibility
				</h2>

				<div>
					<Label for="visibility">Who can see this event?</Label>
					<select
						id="visibility"
						name="visibility"
						value={event.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 (Anyone)</option>
						<option value="board">Board Only</option>
						<option value="admin">Admin Only</option>
					</select>
				</div>
			</div>

			<!-- Actions -->
			<div class="flex flex-col gap-4 border-t border-slate-200 pt-6 sm:flex-row sm:justify-between">
				{#if member?.role === 'admin'}
					<button
						type="button"
						onclick={() => (showDeleteConfirm = true)}
						class="flex items-center justify-center gap-2 rounded-lg border border-red-200 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50"
					>
						<Trash2 class="h-4 w-4" />
						Delete Event
					</button>
				{:else}
					<div></div>
				{/if}

				<div class="flex gap-3">
					<a
						href="/board/events"
						class="flex items-center justify-center rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
					>
						Cancel
					</a>
					<button
						type="submit"
						disabled={isSubmitting}
						class="flex items-center justify-center gap-2 rounded-lg bg-monaco-600 px-6 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>
							Saving...
						{:else}
							<Save class="h-4 w-4" />
							Save Changes
						{/if}
					</button>
				</div>
			</div>
		</form>
	</div>
</div>

<!-- Delete Confirmation Modal -->
{#if showDeleteConfirm}
	<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-md p-6">
			<div class="mb-4 flex items-center justify-between">
				<h3 class="text-lg font-semibold text-red-600">Delete Event</h3>
				<button onclick={() => (showDeleteConfirm = false)} class="rounded p-1 hover:bg-slate-100">
					<X class="h-5 w-5 text-slate-500" />
				</button>
			</div>

			<p class="mb-4 text-slate-600">
				Are you sure you want to delete <strong>{event.title}</strong>? This action cannot be undone.
			</p>

			<p class="mb-6 text-sm text-slate-500">
				All RSVPs and associated data will also be deleted.
			</p>

			<div class="flex gap-3">
				<button
					onclick={() => (showDeleteConfirm = 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>
				<form method="POST" action="?/delete" class="flex-1">
					<button
						type="submit"
						class="w-full rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700"
					>
						Delete Event
					</button>
				</form>
			</div>
		</div>
	</div>
{/if}
