<script lang="ts">
	import { enhance } from '$app/forms';
	import { invalidateAll } from '$app/navigation';
	import {
		Calendar,
		MapPin,
		Users,
		Clock,
		DollarSign,
		ArrowLeft,
		Check,
		X,
		UserPlus,
		ExternalLink,
		CreditCard,
		Loader2
	} from 'lucide-svelte';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { FormMessage, LoadingSpinner } from '$lib/components/auth';
	import AddToCalendarButton from '$lib/components/ui/AddToCalendarButton.svelte';

	let { data, form } = $props();
	let event = $derived(data.event);
	let rsvp = $derived(data.rsvp);
	let member = $derived(data.member);

	// Check if RSVP is pending payment (for paid events)
	let isPendingPayment = $derived(
		rsvp && event?.is_paid && rsvp.payment_status === 'pending'
	);

	let loading = $state(false);
	let guestCount = $state(rsvp?.guest_count || 0);

	// Format date and time
	function formatDateTime(dateStr: string) {
		const date = new Date(dateStr);
		return {
			date: date.toLocaleDateString('en-US', {
				weekday: 'long',
				month: 'long',
				day: 'numeric',
				year: 'numeric'
			}),
			time: date.toLocaleTimeString('en-US', {
				hour: 'numeric',
				minute: '2-digit',
				hour12: true
			})
		};
	}

	const startDateTime = formatDateTime(event?.start_datetime || '');
	const endDateTime = formatDateTime(event?.end_datetime || '');

	// Check if event is in the past
	const isPast = new Date(event?.end_datetime || '') < new Date();

	// Check if RSVP deadline has passed
	const isRsvpClosed = $derived(
		event?.rsvp_deadline_enabled && event?.rsvp_deadline
			? new Date() > new Date(event.rsvp_deadline)
			: false
	);

	// Format RSVP deadline for display
	const rsvpDeadlineDisplay = $derived(
		event?.rsvp_deadline
			? new Date(event.rsvp_deadline).toLocaleDateString('en-US', {
					month: 'short',
					day: 'numeric',
					year: 'numeric',
					hour: 'numeric',
					minute: '2-digit',
					hour12: true
				})
			: null
	);

	// Get type color
	function getTypeColor(color: string | null): string {
		return color || '#6b7280';
	}
</script>

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

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

	{#if event}
		<!-- Event Header -->
		<div class="glass-card overflow-hidden">
			{#if event.cover_image_url}
				<div class="aspect-video w-full">
					<img
						src={event.cover_image_url}
						alt={event.title}
						class="h-full w-full object-cover"
					/>
				</div>
			{/if}

			<div class="p-6">
				<div class="flex flex-wrap items-center gap-2">
					<span
						class="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-sm font-medium"
						style="background-color: {getTypeColor(event.event_type_color)}20; color: {getTypeColor(
							event.event_type_color
						)}"
					>
						{event.event_type_name || 'Event'}
					</span>
					{#if event.is_paid}
						<span
							class="inline-flex items-center gap-1 rounded-full bg-green-100 px-3 py-1 text-sm font-medium text-green-700"
						>
							<DollarSign class="h-3.5 w-3.5" />
							€{event.member_price}
						</span>
					{:else}
						<span
							class="inline-flex rounded-full bg-blue-100 px-3 py-1 text-sm font-medium text-blue-700"
						>
							Free
						</span>
					{/if}
					{#if event.is_full}
						<span
							class="inline-flex rounded-full bg-red-100 px-3 py-1 text-sm font-medium text-red-700"
						>
							Full
						</span>
					{/if}
					{#if isPast}
						<span
							class="inline-flex rounded-full bg-slate-100 px-3 py-1 text-sm font-medium text-slate-700"
						>
							Past Event
						</span>
					{/if}
				</div>

				<h1 class="mt-4 text-2xl font-bold text-slate-900 lg:text-3xl">{event.title}</h1>

				{#if event.description}
					<p class="mt-4 whitespace-pre-wrap text-slate-600">{event.description}</p>
				{/if}
			</div>
		</div>

		<!-- Event Details -->
		<div class="grid gap-6 lg:grid-cols-3">
			<div class="lg:col-span-2 space-y-6">
				<!-- Date & Time -->
				<div class="glass-card p-6">
					<div class="flex items-start justify-between mb-4">
						<h2 class="text-lg font-semibold text-slate-900">Date & Time</h2>
						{#if event && !isPast}
							<AddToCalendarButton
								eventId={event.id}
								eventTitle={event.title}
								startDatetime={event.start_datetime}
								endDatetime={event.end_datetime}
								location={event.location}
								description={event.description}
							/>
						{/if}
					</div>
					<div class="space-y-3">
						<div class="flex items-start gap-3">
							<Calendar class="h-5 w-5 flex-shrink-0 text-monaco-600" />
							<div>
								<p class="font-medium text-slate-900">{startDateTime.date}</p>
								<p class="text-sm text-slate-500">
									{startDateTime.time} - {endDateTime.time}
								</p>
							</div>
						</div>
						{#if event.location}
							<div class="flex items-start gap-3">
								<MapPin class="h-5 w-5 flex-shrink-0 text-monaco-600" />
								<div>
									<p class="font-medium text-slate-900">{event.location}</p>
									{#if event.location_url}
										<a
											href={event.location_url}
											target="_blank"
											rel="noopener noreferrer"
											class="mt-1 inline-flex items-center gap-1 text-sm text-monaco-600 hover:underline"
										>
											View on map
											<ExternalLink class="h-3 w-3" />
										</a>
									{/if}
								</div>
							</div>
						{/if}
					</div>
				</div>

				<!-- Attendees -->
				<div class="glass-card p-6">
					<h2 class="mb-4 text-lg font-semibold text-slate-900">Attendees</h2>
					<div class="flex items-center gap-3">
						<Users class="h-5 w-5 text-monaco-600" />
						<div>
							<p class="font-medium text-slate-900">
								{event.total_attendees}
								{event.max_attendees ? ` / ${event.max_attendees}` : ''} attending
							</p>
							{#if event.waitlist_count > 0}
								<p class="text-sm text-slate-500">{event.waitlist_count} on waitlist</p>
							{/if}
						</div>
					</div>
				</div>
			</div>

			<!-- RSVP Section -->
			<div class="lg:col-span-1">
				<div class="glass-card p-6">
					<h2 class="mb-4 text-lg font-semibold text-slate-900">RSVP</h2>

					{#if form?.error}
						<div class="mb-4">
							<FormMessage type="error" message={form.error} />
						</div>
					{/if}

					{#if form?.success}
						<div class="mb-4">
							<FormMessage type="success" message={form.success} />
						</div>
					{/if}

					{#if event.rsvp_deadline_enabled && rsvpDeadlineDisplay}
						<p class="mb-3 text-xs text-slate-500">
							RSVP deadline: {rsvpDeadlineDisplay}
						</p>
					{/if}

					{#if isPast}
						<p class="text-slate-500">This event has already ended.</p>
					{:else if isRsvpClosed}
						<div class="rounded-lg bg-amber-50 border border-amber-200 p-4">
							<p class="font-medium text-amber-700">RSVPs are closed</p>
							<p class="mt-1 text-sm text-amber-600">
								The RSVP deadline was {rsvpDeadlineDisplay}.
							</p>
						</div>
					{:else if rsvp}
						<!-- Existing RSVP -->
						<div
							class="mb-4 rounded-lg {isPendingPayment
								? 'bg-amber-50 border border-amber-200'
								: rsvp.status === 'confirmed'
									? 'bg-green-50 border border-green-200'
									: rsvp.status === 'waitlist'
										? 'bg-yellow-50 border border-yellow-200'
										: rsvp.status === 'maybe'
											? 'bg-blue-50 border border-blue-200'
											: 'bg-slate-50 border border-slate-200'} p-4"
						>
							<div class="flex items-center gap-2">
								{#if isPendingPayment}
									<Loader2 class="h-5 w-5 text-amber-600 animate-spin" />
									<span class="font-medium text-amber-700">Processing - Payment Required</span>
								{:else if rsvp.status === 'confirmed'}
									<Check class="h-5 w-5 text-green-600" />
									<span class="font-medium text-green-700">You're attending!</span>
								{:else if rsvp.status === 'waitlist'}
									<Clock class="h-5 w-5 text-yellow-600" />
									<span class="font-medium text-yellow-700">You're on the waitlist</span>
								{:else if rsvp.status === 'maybe'}
									<Clock class="h-5 w-5 text-blue-600" />
									<span class="font-medium text-blue-700">You're tentative</span>
								{:else if rsvp.status === 'declined'}
									<X class="h-5 w-5 text-slate-600" />
									<span class="font-medium text-slate-700">You declined</span>
								{/if}
							</div>
							{#if isPendingPayment && rsvp.payment_amount}
								<div class="mt-3 rounded-md bg-white p-3 border border-amber-200">
									<div class="flex items-center justify-between">
										<span class="text-sm text-slate-600">Amount Due:</span>
										<span class="font-semibold text-slate-900">€{rsvp.payment_amount.toFixed(2)}</span>
									</div>
									<p class="mt-2 text-xs text-amber-600">
										Your RSVP will be confirmed once payment is received.
									</p>
								</div>
							{/if}
							{#if rsvp.guest_count > 0}
								<p class="mt-2 text-sm text-slate-600">
									+{rsvp.guest_count} guest{rsvp.guest_count > 1 ? 's' : ''}
								</p>
							{/if}
						</div>

						<!-- Change RSVP Status -->
						{#if rsvp.status !== 'cancelled'}
							<div class="space-y-3">
								<p class="text-sm font-medium text-slate-700">Change your response:</p>
								<div class="flex flex-wrap gap-2">
									{#if rsvp.status !== 'confirmed' && !event.is_full}
										<form
											method="POST"
											action="?/updateRsvp"
											use:enhance={() => {
												loading = true;
												return async ({ update, result }) => {
													loading = false;
													if (result.type === 'success') {
														await invalidateAll();
													}
													await update();
												};
											}}
											class="inline"
										>
											<input type="hidden" name="status" value="confirmed" />
											<input type="hidden" name="guest_count" value={rsvp.guest_count} />
											<Button
												type="submit"
												variant="outline"
												size="sm"
												disabled={loading}
												class="border-green-300 text-green-700 hover:bg-green-50"
											>
												<Check class="mr-1 h-3.5 w-3.5" />
												Going
											</Button>
										</form>
									{/if}
									{#if rsvp.status !== 'maybe'}
										<form
											method="POST"
											action="?/updateRsvp"
											use:enhance={() => {
												loading = true;
												return async ({ update, result }) => {
													loading = false;
													if (result.type === 'success') {
														await invalidateAll();
													}
													await update();
												};
											}}
											class="inline"
										>
											<input type="hidden" name="status" value="maybe" />
											<input type="hidden" name="guest_count" value={rsvp.guest_count} />
											<Button
												type="submit"
												variant="outline"
												size="sm"
												disabled={loading}
												class="border-blue-300 text-blue-700 hover:bg-blue-50"
											>
												<Clock class="mr-1 h-3.5 w-3.5" />
												Maybe
											</Button>
										</form>
									{/if}
									{#if rsvp.status !== 'declined'}
										<form
											method="POST"
											action="?/updateRsvp"
											use:enhance={() => {
												loading = true;
												return async ({ update, result }) => {
													loading = false;
													if (result.type === 'success') {
														await invalidateAll();
													}
													await update();
												};
											}}
											class="inline"
										>
											<input type="hidden" name="status" value="declined" />
											<input type="hidden" name="guest_count" value="0" />
											<Button
												type="submit"
												variant="outline"
												size="sm"
												disabled={loading}
												class="border-slate-300 text-slate-700 hover:bg-slate-50"
											>
												<X class="mr-1 h-3.5 w-3.5" />
												Can't Go
											</Button>
										</form>
									{/if}
								</div>

								<!-- Cancel RSVP (remove completely) -->
								<form
									method="POST"
									action="?/cancel"
									use:enhance={() => {
										loading = true;
										return async ({ update, result }) => {
											loading = false;
											if (result.type === 'success') {
												await invalidateAll();
											}
											await update();
										};
									}}
								>
									<Button
										type="submit"
										variant="ghost"
										size="sm"
										class="text-red-600 hover:bg-red-50 hover:text-red-700"
										disabled={loading}
									>
										{#if loading}
											<LoadingSpinner size="sm" class="mr-2" />
										{/if}
										Remove my RSVP
									</Button>
								</form>
							</div>
						{/if}
					{:else}
						<!-- New RSVP Form -->
						<form
							method="POST"
							action="?/rsvp"
							use:enhance={() => {
								loading = true;
								return async ({ update, result }) => {
									loading = false;
									if (result.type === 'success') {
										await invalidateAll();
									}
									await update();
								};
							}}
							class="space-y-4"
						>
							{#if event.max_guests_per_member > 0}
								<div class="space-y-2">
									<Label for="guest_count">Additional guests</Label>
									<Input
										id="guest_count"
										name="guest_count"
										type="number"
										min="0"
										max={event.max_guests_per_member}
										bind:value={guestCount}
										disabled={loading}
										class="h-11"
									/>
									<p class="text-xs text-slate-500">
										Max {event.max_guests_per_member} guest{event.max_guests_per_member > 1
											? 's'
											: ''} allowed
									</p>
								</div>
							{/if}

							{#if event.is_paid}
								<div class="rounded-lg bg-slate-50 p-3">
									<p class="text-sm font-medium text-slate-900">
										Total: €{(event.member_price * (1 + guestCount)).toFixed(2)}
									</p>
									<p class="text-xs text-slate-500">
										Payment instructions will be sent after RSVP
									</p>
								</div>
							{/if}

							<Button
								type="submit"
								variant="monaco"
								class="w-full"
								disabled={loading || event.is_full}
							>
								{#if loading}
									<LoadingSpinner size="sm" class="mr-2" />
									Submitting...
								{:else if event.is_full}
									Join Waitlist
								{:else}
									<UserPlus class="mr-2 h-4 w-4" />
									RSVP Now
								{/if}
							</Button>
						</form>
					{/if}
				</div>
			</div>
		</div>
	{:else}
		<div class="glass-card p-12 text-center">
			<p class="text-slate-600">Event not found.</p>
			<a href="/events" class="mt-4 inline-block text-monaco-600 hover:underline">
				View all events
			</a>
		</div>
	{/if}
</div>
