<script lang="ts">
	import { Calendar, MapPin, Users, Clock, Grid, List, ChevronLeft, ChevronRight, Filter } from 'lucide-svelte';
	import { Button } from '$lib/components/ui/button';
	import type { EventWithCounts } from '$lib/types/database';

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

	let viewMode = $state<'list' | 'calendar'>('list');
	let currentMonth = $state(new Date());
	let selectedTypeIds = $state<Set<string>>(new Set());
	let showFilters = $state(false);

	// Filter events by selected types
	const filteredEvents = $derived(
		selectedTypeIds.size === 0
			? events
			: (events || []).filter((e: EventWithCounts) => selectedTypeIds.has(e.event_type_id))
	);

	function toggleTypeFilter(typeId: string) {
		const next = new Set(selectedTypeIds);
		if (next.has(typeId)) {
			next.delete(typeId);
		} else {
			next.add(typeId);
		}
		selectedTypeIds = next;
	}

	function clearFilters() {
		selectedTypeIds = new Set();
	}

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

	// Check if event is today
	function isToday(dateStr: string): boolean {
		const eventDate = new Date(dateStr).toDateString();
		return eventDate === new Date().toDateString();
	}

	// Check if event is this week
	function isThisWeek(dateStr: string): boolean {
		const eventDate = new Date(dateStr);
		const today = new Date();
		const weekStart = new Date(today);
		weekStart.setDate(today.getDate() - today.getDay());
		const weekEnd = new Date(weekStart);
		weekEnd.setDate(weekStart.getDate() + 7);
		return eventDate >= weekStart && eventDate < weekEnd;
	}

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

	// Group events by date
	function groupEventsByDate(events: EventWithCounts[]) {
		const groups: { date: string; events: EventWithCounts[] }[] = [];
		let currentDate = '';

		for (const event of events) {
			const eventDate = new Date(event.start_datetime).toDateString();
			if (eventDate !== currentDate) {
				currentDate = eventDate;
				groups.push({ date: eventDate, events: [event] });
			} else {
				groups[groups.length - 1].events.push(event);
			}
		}

		return groups;
	}

	const groupedEvents = $derived(groupEventsByDate(filteredEvents || []));

	// Calendar helpers
	function getDaysInMonth(date: Date) {
		const year = date.getFullYear();
		const month = date.getMonth();
		const firstDay = new Date(year, month, 1);
		const lastDay = new Date(year, month + 1, 0);
		const daysInMonth = lastDay.getDate();
		const startingDay = firstDay.getDay();

		const days = [];
		// Add empty cells for days before the first day of the month
		for (let i = 0; i < startingDay; i++) {
			days.push(null);
		}
		// Add the days of the month
		for (let i = 1; i <= daysInMonth; i++) {
			days.push(new Date(year, month, i));
		}
		return days;
	}

	function getEventsForDate(date: Date | null) {
		if (!date) return [];
		const dateStr = date.toDateString();
		return (filteredEvents || []).filter((e: EventWithCounts) => new Date(e.start_datetime).toDateString() === dateStr);
	}

	function prevMonth() {
		currentMonth = new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1, 1);
	}

	function nextMonth() {
		currentMonth = new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 1);
	}

	const calendarDays = $derived(getDaysInMonth(currentMonth));
	const monthName = $derived(
		currentMonth.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })
	);
</script>

<svelte:head>
	<title>Events | Monaco USA</title>
</svelte:head>

<div class="space-y-6">
	<!-- Header -->
	<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">Events</h1>
			<p class="text-slate-500">Upcoming events and activities</p>
		</div>

		<div class="flex items-center gap-2">
			{#if eventTypes.length > 0}
				<button
					onclick={() => (showFilters = !showFilters)}
					class="flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium transition-colors hover:bg-slate-50 {selectedTypeIds.size > 0 ? 'border-monaco-300 text-monaco-700' : 'text-slate-600'}"
				>
					<Filter class="h-4 w-4" />
					Filter
					{#if selectedTypeIds.size > 0}
						<span class="rounded-full bg-monaco-100 px-1.5 py-0.5 text-xs font-bold text-monaco-700">{selectedTypeIds.size}</span>
					{/if}
				</button>
			{/if}
			<div class="flex rounded-lg border border-slate-200 bg-white p-1">
				<button
					onclick={() => (viewMode = 'list')}
					class="flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors {viewMode ===
					'list'
						? 'bg-monaco-100 text-monaco-700'
						: 'text-slate-600 hover:bg-slate-50'}"
				>
					<List class="h-4 w-4" />
					List
				</button>
				<button
					onclick={() => (viewMode = 'calendar')}
					class="flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors {viewMode ===
					'calendar'
						? 'bg-monaco-100 text-monaco-700'
						: 'text-slate-600 hover:bg-slate-50'}"
				>
					<Grid class="h-4 w-4" />
					Calendar
				</button>
			</div>
		</div>
	</div>

	<!-- Event Type Filters -->
	{#if showFilters && eventTypes.length > 0}
		<div class="glass-card flex flex-wrap items-center gap-2 p-4">
			<span class="text-sm font-medium text-slate-600">Event Type:</span>
			{#each eventTypes as type}
				<button
					onclick={() => toggleTypeFilter(type.id)}
					class="flex items-center gap-1.5 rounded-full border px-3 py-1 text-sm font-medium transition-colors {selectedTypeIds.has(type.id)
						? 'border-transparent text-white'
						: 'border-slate-200 bg-white text-slate-600 hover:bg-slate-50'}"
					style={selectedTypeIds.has(type.id) ? `background-color: ${type.color || '#6b7280'}` : ''}
				>
					<span
						class="h-2 w-2 rounded-full"
						style="background-color: {type.color || '#6b7280'}"
					></span>
					{type.name}
				</button>
			{/each}
			{#if selectedTypeIds.size > 0}
				<button
					onclick={clearFilters}
					class="ml-2 text-sm text-slate-500 hover:text-slate-700"
				>
					Clear all
				</button>
			{/if}
			<span class="ml-auto text-sm text-slate-500">
				{filteredEvents.length} event{filteredEvents.length !== 1 ? 's' : ''}
			</span>
		</div>
	{/if}

	{#if viewMode === 'list'}
		<!-- List View -->
		<div class="space-y-6">
			{#if groupedEvents.length === 0}
				<div class="glass-card 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 upcoming events</h3>
					<p class="mt-1 text-slate-500">Check back later for new events and activities.</p>
				</div>
			{:else}
				{#each groupedEvents as group}
					{@const groupDate = new Date(group.date)}
					<div>
						<!-- Date Header -->
						<div class="mb-3 flex items-center gap-3">
							<div
								class="flex h-12 w-12 flex-col items-center justify-center rounded-lg {isToday(
									group.date
								)
									? 'bg-monaco-600 text-white'
									: 'bg-slate-100 text-slate-600'}"
							>
								<span class="text-xs font-medium uppercase">
									{groupDate.toLocaleDateString('en-US', { month: 'short' })}
								</span>
								<span class="text-lg font-bold">
									{groupDate.getDate()}
								</span>
							</div>
							<div>
								<p class="font-medium text-slate-900">
									{isToday(group.date)
										? 'Today'
										: groupDate.toLocaleDateString('en-US', { weekday: 'long' })}
								</p>
								<p class="text-sm text-slate-500">
									{groupDate.toLocaleDateString('en-US', {
										month: 'long',
										day: 'numeric',
										year: 'numeric'
									})}
								</p>
							</div>
						</div>

						<!-- Events for this date -->
						<div class="space-y-3">
							{#each group.events as event}
								{@const { time } = formatDateTime(event.start_datetime)}
								<a
									href="/events/{event.id}"
									class="glass-card block p-4 transition-all hover:shadow-md"
								>
									<div class="flex items-start gap-4">
										<!-- Time column -->
										<div class="w-16 flex-shrink-0 text-right">
											<span class="text-sm font-medium text-slate-600">{time}</span>
										</div>

										<!-- Event type indicator -->
										<div
											class="mt-1.5 h-3 w-3 flex-shrink-0 rounded-full"
											style="background-color: {getTypeColor(event.event_type_color)}"
										></div>

										<!-- Event details -->
										<div class="flex-1 min-w-0">
											<div class="flex items-center gap-2">
												<span class="text-xs font-medium text-slate-500">
													{event.event_type_name || 'Event'}
												</span>
												{#if event.is_paid}
													<span
														class="rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700"
													>
														€{event.member_price}
													</span>
												{/if}
											</div>
											<h3 class="mt-1 font-semibold text-slate-900">{event.title}</h3>
											{#if event.description}
												<p class="mt-1 line-clamp-2 text-sm text-slate-500">
													{event.description}
												</p>
											{/if}
											<div
												class="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-slate-500"
											>
												{#if event.location}
													<span class="flex items-center gap-1">
														<MapPin class="h-3.5 w-3.5" />
														{event.location}
													</span>
												{/if}
												<span class="flex items-center gap-1">
													<Users class="h-3.5 w-3.5" />
													{event.total_attendees}
													{event.max_attendees ? ` / ${event.max_attendees}` : ''} attending
												</span>
												{#if event.is_full}
													<span
														class="rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700"
													>
														Full
													</span>
												{/if}
											</div>
										</div>
									</div>
								</a>
							{/each}
						</div>
					</div>
				{/each}
			{/if}
		</div>
	{:else}
		<!-- Calendar View -->
		<div class="glass-card overflow-hidden">
			<!-- Calendar Header -->
			<div class="flex items-center justify-between border-b border-slate-200 px-6 py-4">
				<button
					onclick={prevMonth}
					class="rounded-lg p-2 hover:bg-slate-100"
					aria-label="Previous month"
				>
					<ChevronLeft class="h-5 w-5 text-slate-600" />
				</button>
				<h2 class="text-lg font-semibold text-slate-900">{monthName}</h2>
				<button
					onclick={nextMonth}
					class="rounded-lg p-2 hover:bg-slate-100"
					aria-label="Next month"
				>
					<ChevronRight class="h-5 w-5 text-slate-600" />
				</button>
			</div>

			<!-- Calendar Grid -->
			<div class="p-4">
				<!-- Weekday headers -->
				<div class="mb-2 grid grid-cols-7 text-center text-xs font-medium text-slate-500">
					<div>Sun</div>
					<div>Mon</div>
					<div>Tue</div>
					<div>Wed</div>
					<div>Thu</div>
					<div>Fri</div>
					<div>Sat</div>
				</div>

				<!-- Days grid -->
				<div class="grid grid-cols-7 gap-1">
					{#each calendarDays as day}
						{@const dayEvents = getEventsForDate(day)}
						<div
							class="min-h-24 rounded-lg border border-slate-100 p-1 {day
								? 'bg-white'
								: 'bg-slate-50'}"
						>
							{#if day}
								<div
									class="mb-1 text-right text-sm {day.toDateString() === new Date().toDateString()
										? 'font-bold text-monaco-600'
										: 'text-slate-600'}"
								>
									{day.getDate()}
								</div>
								{#each dayEvents.slice(0, 2) as event}
									<a
										href="/events/{event.id}"
										class="mb-1 block truncate rounded px-1 py-0.5 text-xs"
										style="background-color: {getTypeColor(event.event_type_color)}20; color: {getTypeColor(
											event.event_type_color
										)}"
									>
										{event.title}
									</a>
								{/each}
								{#if dayEvents.length > 2}
									<span class="text-xs text-slate-500">+{dayEvents.length - 2} more</span>
								{/if}
							{/if}
						</div>
					{/each}
				</div>
			</div>
		</div>
	{/if}
</div>
