<script lang="ts">
	import { enhance } from '$app/forms';
	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';
	import {
		Calendar,
		Clock,
		MapPin,
		Users,
		DollarSign,
		ExternalLink,
		CheckCircle,
		AlertCircle
	} from 'lucide-svelte';

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

	let loading = $state(false);
	let guestCount = $state(0);

	const eventDate = new Date(event.start_datetime);
	const eventEndDate = new Date(event.end_datetime);

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

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

	function formatCurrency(amount: number): string {
		return new Intl.NumberFormat('fr-MC', {
			style: 'currency',
			currency: 'EUR'
		}).format(amount);
	}

	const spotsRemaining = event.max_attendees
		? Math.max(0, event.max_attendees - event.total_attendees)
		: null;
</script>

<svelte:head>
	<title>{event.title} | Monaco USA</title>
	<meta name="description" content={event.description || `Join us for ${event.title}`} />
</svelte:head>

<div class="relative min-h-screen bg-slate-50">
	<!-- Hero Header -->
	<div class="relative bg-gradient-to-br from-slate-900 via-slate-800 to-monaco-900 py-16 text-white">
		<div class="absolute inset-0 bg-[url('/monaco_high_res.jpg')] bg-cover bg-center opacity-20"></div>
		<div class="relative mx-auto max-w-4xl px-4">
			<div class="flex items-center gap-4 mb-4">
				<a href="/" class="flex items-center gap-2">
					<img src="/MONACOUSA-Flags_376x376.png" alt="Monaco USA" class="h-12 w-12 rounded-lg bg-white/90 p-1" />
					<span class="text-xl font-bold">Monaco <span class="text-monaco-300">USA</span></span>
				</a>
			</div>

			{#if event.event_type_name}
				<span
					class="inline-block rounded-full px-3 py-1 text-sm font-medium"
					style="background-color: {event.event_type_color}40; color: {event.event_type_color}"
				>
					{event.event_type_name}
				</span>
			{/if}

			<h1 class="mt-4 text-4xl font-bold md:text-5xl">{event.title}</h1>

			<div class="mt-6 flex flex-wrap items-center gap-6 text-white/90">
				<div class="flex items-center gap-2">
					<Calendar class="h-5 w-5 text-monaco-300" />
					<span>{formatDate(eventDate)}</span>
				</div>
				{#if !event.all_day}
					<div class="flex items-center gap-2">
						<Clock class="h-5 w-5 text-monaco-300" />
						<span>{formatTime(eventDate)} - {formatTime(eventEndDate)}</span>
					</div>
				{/if}
				{#if event.location}
					<div class="flex items-center gap-2">
						<MapPin class="h-5 w-5 text-monaco-300" />
						<span>{event.location}</span>
					</div>
				{/if}
			</div>
		</div>
	</div>

	<!-- Content -->
	<div class="mx-auto max-w-4xl px-4 py-12">
		<div class="grid gap-8 lg:grid-cols-3">
			<!-- Main Content -->
			<div class="lg:col-span-2 space-y-8">
				<!-- Description -->
				{#if event.description}
					<div class="rounded-2xl bg-white p-8 shadow-sm">
						<h2 class="mb-4 text-xl font-semibold text-slate-900">About This Event</h2>
						<div class="prose prose-slate max-w-none">
							{@html event.description.replace(/\n/g, '<br />')}
						</div>
					</div>
				{/if}

				<!-- Event Details -->
				<div class="rounded-2xl bg-white p-8 shadow-sm">
					<div class="flex items-start justify-between mb-6">
						<h2 class="text-xl font-semibold text-slate-900">Event Details</h2>
						<AddToCalendarButton
							eventId={event.id}
							eventTitle={event.title}
							startDatetime={event.start_datetime}
							endDatetime={event.end_datetime}
							location={event.location}
							description={event.description}
							isPublic={true}
						/>
					</div>

					<div class="space-y-4">
						<div class="flex items-start gap-4">
							<div class="flex h-10 w-10 items-center justify-center rounded-full bg-monaco-100">
								<Calendar class="h-5 w-5 text-monaco-600" />
							</div>
							<div>
								<p class="font-medium text-slate-900">Date & Time</p>
								<p class="text-slate-600">
									{formatDate(eventDate)}
									{#if !event.all_day}
										<br />{formatTime(eventDate)} - {formatTime(eventEndDate)} ({event.timezone})
									{:else}
										<br />All day event
									{/if}
								</p>
							</div>
						</div>

						{#if event.location}
							<div class="flex items-start gap-4">
								<div class="flex h-10 w-10 items-center justify-center rounded-full bg-monaco-100">
									<MapPin class="h-5 w-5 text-monaco-600" />
								</div>
								<div>
									<p class="font-medium text-slate-900">Location</p>
									<p class="text-slate-600">{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}

						{#if event.is_paid}
							<div class="flex items-start gap-4">
								<div class="flex h-10 w-10 items-center justify-center rounded-full bg-green-100">
									<DollarSign class="h-5 w-5 text-green-600" />
								</div>
								<div>
									<p class="font-medium text-slate-900">Price</p>
									<p class="text-slate-600">
										Non-members: {formatCurrency(event.non_member_price)}
										{#if event.pricing_notes}
											<br /><span class="text-sm">{event.pricing_notes}</span>
										{/if}
									</p>
								</div>
							</div>
						{/if}

						<div class="flex items-start gap-4">
							<div class="flex h-10 w-10 items-center justify-center rounded-full bg-blue-100">
								<Users class="h-5 w-5 text-blue-600" />
							</div>
							<div>
								<p class="font-medium text-slate-900">Attendance</p>
								<p class="text-slate-600">
									{event.total_attendees} registered
									{#if event.max_attendees}
										/ {event.max_attendees} capacity
									{/if}
								</p>
								{#if event.waitlist_count > 0}
									<p class="text-sm text-amber-600">{event.waitlist_count} on waitlist</p>
								{/if}
							</div>
						</div>
					</div>
				</div>
			</div>

			<!-- RSVP Sidebar -->
			<div class="lg:col-span-1">
				<div class="sticky top-8 rounded-2xl bg-white p-6 shadow-sm">
					{#if form?.success}
						<div class="text-center">
							<div class="mb-4 flex justify-center">
								<div class="flex h-16 w-16 items-center justify-center rounded-full bg-green-100">
									<CheckCircle class="h-8 w-8 text-green-600" />
								</div>
							</div>
							<h3 class="text-xl font-semibold text-slate-900">You're Registered!</h3>
							<p class="mt-2 text-slate-600">{form.success}</p>
						</div>
					{:else}
						<h3 class="text-xl font-semibold text-slate-900">Register for This Event</h3>

						{#if spotsRemaining !== null && spotsRemaining <= 5}
							<div class="mt-4 flex items-center gap-2 rounded-lg bg-amber-50 p-3 text-amber-700">
								<AlertCircle class="h-5 w-5 shrink-0" />
								<span class="text-sm">
									{#if spotsRemaining === 0}
										Event is full - Join waitlist
									{:else}
										Only {spotsRemaining} spot{spotsRemaining === 1 ? '' : 's'} left!
									{/if}
								</span>
							</div>
						{/if}

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

						<form
							method="POST"
							action="?/rsvp"
							use:enhance={() => {
								loading = true;
								return async ({ update }) => {
									loading = false;
									await update();
								};
							}}
							class="mt-6 space-y-4"
						>
							<div class="space-y-2">
								<Label for="full_name">Full Name *</Label>
								<Input
									id="full_name"
									name="full_name"
									type="text"
									required
									disabled={loading}
									placeholder="John Smith"
									class="h-11"
								/>
							</div>

							<div class="space-y-2">
								<Label for="email">Email *</Label>
								<Input
									id="email"
									name="email"
									type="email"
									required
									disabled={loading}
									placeholder="john@example.com"
									class="h-11"
								/>
							</div>

							<div class="space-y-2">
								<Label for="phone">Phone (optional)</Label>
								<Input
									id="phone"
									name="phone"
									type="tel"
									disabled={loading}
									placeholder="+1 (555) 123-4567"
									class="h-11"
								/>
							</div>

							{#if event.max_guests_per_member !== 0}
								<div class="space-y-2">
									<Label for="guest_count">Additional Guests</Label>
									<select
										id="guest_count"
										name="guest_count"
										bind:value={guestCount}
										disabled={loading}
										class="h-11 w-full rounded-lg border border-slate-200 px-3 focus:border-monaco-500 focus:outline-none focus:ring-2 focus:ring-monaco-500/20"
									>
										{#each Array(Math.min((event.max_guests_per_member || 5) + 1, 6)) as _, i}
											<option value={i}>{i} guest{i !== 1 ? 's' : ''}</option>
										{/each}
									</select>
								</div>
							{/if}

							{#if event.is_paid}
								<div class="rounded-lg bg-slate-50 p-4">
									<div class="flex items-center justify-between">
										<span class="text-slate-600">Total</span>
										<span class="text-xl font-semibold text-slate-900">
											{formatCurrency(event.non_member_price * (1 + guestCount))}
										</span>
									</div>
									<p class="mt-1 text-xs text-slate-500">Payment details will be provided after registration</p>
								</div>
							{/if}

							<Button
								type="submit"
								variant="monaco"
								size="lg"
								class="w-full"
								disabled={loading}
							>
								{#if loading}
									<LoadingSpinner size="sm" class="mr-2" />
									Registering...
								{:else if spotsRemaining === 0}
									Join Waitlist
								{:else}
									Register Now
								{/if}
							</Button>

							<p class="text-center text-xs text-slate-500">
								Already a Monaco USA member?
								<a href="/login" class="text-monaco-600 hover:underline">Sign in</a>
								to RSVP with your account.
							</p>
						</form>
					{/if}
				</div>
			</div>
		</div>
	</div>

	<!-- Footer -->
	<footer class="border-t border-slate-200 bg-white py-8">
		<div class="mx-auto max-w-4xl px-4 text-center">
			<p class="text-sm text-slate-500">
				&copy; 2026 Monaco USA. All rights reserved.
			</p>
			<p class="mt-2 text-sm text-slate-500">
				<a href="/" class="text-monaco-600 hover:underline">Home</a>
				<span class="mx-2">|</span>
				<a href="/login" class="text-monaco-600 hover:underline">Member Login</a>
			</p>
		</div>
	</footer>
</div>
