<script lang="ts">
	import { get } from '$lib/api/client';

	interface TripSummary {
		id: string;
		name: string;
		start_date: string;
		end_date: string;
	}

	interface Stats {
		total_trips: number;
		cities_visited: number;
		countries_visited: number;
		total_points_redeemed: number;
		total_activities: number;
		trips_by_year: Record<string, TripSummary[]>;
		cities_by_country: Record<string, string[]>;
		points_by_year: Record<string, number>;
		points_by_category: { flights: number; hotels: number; activities: number };
	}

	let stats = $state<Stats | null>(null);

	let tripsModal = $state<HTMLDialogElement | null>(null);
	let citiesModal = $state<HTMLDialogElement | null>(null);
	let countriesModal = $state<HTMLDialogElement | null>(null);
	let pointsModal = $state<HTMLDialogElement | null>(null);

	$effect(() => {
		loadStats();
	});

	async function loadStats() {
		try {
			stats = await get<Stats>('/api/stats');
		} catch (e) {
			console.error('Failed to load stats:', e);
		}
	}

	function formatNumber(n: number): string {
		return n.toLocaleString();
	}

	function formatDate(d: string): string {
		if (!d) return '';
		const date = new Date(d + 'T00:00:00');
		return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
	}

	function formatDateRange(start: string, end: string): string {
		if (!start) return '';
		const s = formatDate(start);
		const e = end ? formatDate(end) : '';
		return e ? `${s} - ${e}` : s;
	}

	function maxPoints(): number {
		if (!stats?.points_by_year) return 1;
		return Math.max(...Object.values(stats.points_by_year), 1);
	}

	function maxCategoryPoints(): number {
		if (!stats?.points_by_category) return 1;
		return Math.max(...Object.values(stats.points_by_category), 1);
	}
</script>

{#if stats}
	<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
		<!-- Total Trips -->
		<div
			class="card bg-gradient-to-br from-primary/10 to-primary/5 border border-primary/20 shadow-md hover:shadow-xl transition-shadow duration-300 cursor-pointer"
			onclick={() => tripsModal?.showModal()}
		>
			<div class="card-body p-4 flex flex-row items-center gap-3">
				<div class="p-3 rounded-2xl bg-primary/15">
					<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<path d="M3 7l6-3 6 3 6-3v13l-6 3-6-3-6 3V7z"/><path d="M9 4v13"/><path d="M15 7v13"/>
					</svg>
				</div>
				<div>
					<div class="text-2xl font-bold text-base-content">{formatNumber(stats.total_trips)}</div>
					<div class="text-xs text-base-content/50 font-medium uppercase tracking-wide">Trips</div>
				</div>
			</div>
		</div>

		<!-- Cities Visited -->
		<div
			class="card bg-gradient-to-br from-info/10 to-info/5 border border-info/20 shadow-md hover:shadow-xl transition-shadow duration-300 cursor-pointer"
			onclick={() => citiesModal?.showModal()}
		>
			<div class="card-body p-4 flex flex-row items-center gap-3">
				<div class="p-3 rounded-2xl bg-info/15">
					<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-info" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<path d="M3 21h18"/><path d="M5 21V7l8-4v18"/><path d="M19 21V11l-6-4"/><path d="M9 9h.01"/><path d="M9 12h.01"/><path d="M9 15h.01"/><path d="M9 18h.01"/>
					</svg>
				</div>
				<div>
					<div class="text-2xl font-bold text-base-content">{formatNumber(stats.cities_visited)}</div>
					<div class="text-xs text-base-content/50 font-medium uppercase tracking-wide">Cities Visited</div>
				</div>
			</div>
		</div>

		<!-- Countries Visited -->
		<div
			class="card bg-gradient-to-br from-success/10 to-success/5 border border-success/20 shadow-md hover:shadow-xl transition-shadow duration-300 cursor-pointer"
			onclick={() => countriesModal?.showModal()}
		>
			<div class="card-body p-4 flex flex-row items-center gap-3">
				<div class="p-3 rounded-2xl bg-success/15">
					<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-success" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>
					</svg>
				</div>
				<div>
					<div class="text-2xl font-bold text-base-content">{formatNumber(stats.countries_visited)}</div>
					<div class="text-xs text-base-content/50 font-medium uppercase tracking-wide">Countries</div>
				</div>
			</div>
		</div>

		<!-- Points Redeemed -->
		<div
			class="card bg-gradient-to-br from-accent/10 to-accent/5 border border-accent/20 shadow-md hover:shadow-xl transition-shadow duration-300 cursor-pointer"
			onclick={() => pointsModal?.showModal()}
		>
			<div class="card-body p-4 flex flex-row items-center gap-3">
				<div class="p-3 rounded-2xl bg-accent/15">
					<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
					</svg>
				</div>
				<div>
					<div class="text-2xl font-bold text-base-content">{formatNumber(stats.total_points_redeemed)}</div>
					<div class="text-xs text-base-content/50 font-medium uppercase tracking-wide">Miles Redeemed</div>
				</div>
			</div>
		</div>
	</div>

	<!-- Trips Modal -->
	<dialog bind:this={tripsModal} class="modal modal-bottom sm:modal-middle">
		<div class="modal-box max-w-2xl">
			<form method="dialog">
				<button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
			</form>
			<h3 class="font-bold text-lg flex items-center gap-2">
				<div class="p-2 rounded-xl bg-primary/15">
					<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<path d="M3 7l6-3 6 3 6-3v13l-6 3-6-3-6 3V7z"/><path d="M9 4v13"/><path d="M15 7v13"/>
					</svg>
				</div>
				Trips
				<span class="badge badge-primary">{stats.total_trips}</span>
			</h3>
			<div class="mt-4 max-h-[60vh] overflow-y-auto">
				{#each Object.entries(stats.trips_by_year) as [year, trips]}
					<div class="divider text-base-content/50 text-sm">{year}</div>
					<div class="space-y-2">
						{#each trips as trip}
							<a
								href="/trip/{trip.id}"
								class="flex items-center justify-between p-3 rounded-lg bg-base-200/50 hover:bg-base-200 transition-colors"
								onclick={() => tripsModal?.close()}
							>
								<span class="font-medium">{trip.name}</span>
								<span class="text-sm text-base-content/50">{formatDateRange(trip.start_date, trip.end_date)}</span>
							</a>
						{/each}
					</div>
				{/each}
			</div>
		</div>
		<form method="dialog" class="modal-backdrop">
			<button>close</button>
		</form>
	</dialog>

	<!-- Cities Modal -->
	<dialog bind:this={citiesModal} class="modal modal-bottom sm:modal-middle">
		<div class="modal-box max-w-2xl">
			<form method="dialog">
				<button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
			</form>
			<h3 class="font-bold text-lg flex items-center gap-2">
				<div class="p-2 rounded-xl bg-info/15">
					<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-info" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<path d="M3 21h18"/><path d="M5 21V7l8-4v18"/><path d="M19 21V11l-6-4"/><path d="M9 9h.01"/><path d="M9 12h.01"/><path d="M9 15h.01"/><path d="M9 18h.01"/>
					</svg>
				</div>
				Cities Visited
				<span class="badge badge-info">{stats.cities_visited}</span>
			</h3>
			<div class="mt-4 max-h-[60vh] overflow-y-auto">
				{#each Object.entries(stats.cities_by_country) as [country, cities]}
					<div class="divider text-base-content/50 text-sm">{country}</div>
					<div class="flex flex-wrap gap-2">
						{#each cities as city}
							<span class="badge badge-outline badge-lg">{city}</span>
						{/each}
					</div>
				{/each}
			</div>
		</div>
		<form method="dialog" class="modal-backdrop">
			<button>close</button>
		</form>
	</dialog>

	<!-- Countries Modal -->
	<dialog bind:this={countriesModal} class="modal modal-bottom sm:modal-middle">
		<div class="modal-box max-w-2xl">
			<form method="dialog">
				<button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
			</form>
			<h3 class="font-bold text-lg flex items-center gap-2">
				<div class="p-2 rounded-xl bg-success/15">
					<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-success" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>
					</svg>
				</div>
				Countries Visited
				<span class="badge badge-success">{stats.countries_visited}</span>
			</h3>
			<div class="mt-4 max-h-[60vh] overflow-y-auto space-y-2">
				{#each Object.entries(stats.cities_by_country) as [country, cities]}
					<div class="flex items-center justify-between p-3 rounded-lg bg-base-200/50">
						<span class="font-medium">{country}</span>
						<span class="badge badge-success badge-outline">{cities.length} {cities.length === 1 ? 'city' : 'cities'}</span>
					</div>
				{/each}
			</div>
		</div>
		<form method="dialog" class="modal-backdrop">
			<button>close</button>
		</form>
	</dialog>

	<!-- Points Modal -->
	<dialog bind:this={pointsModal} class="modal modal-bottom sm:modal-middle">
		<div class="modal-box max-w-2xl">
			<form method="dialog">
				<button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
			</form>
			<h3 class="font-bold text-lg flex items-center gap-2">
				<div class="p-2 rounded-xl bg-accent/15">
					<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
					</svg>
				</div>
				Miles Redeemed
				<span class="badge badge-accent">{formatNumber(stats.total_points_redeemed)}</span>
			</h3>
			<div class="mt-4 max-h-[60vh] overflow-y-auto">
				<!-- By Year -->
				<div class="divider text-base-content/50 text-sm">By Year</div>
				<div class="space-y-3">
					{#each Object.entries(stats.points_by_year) as [year, points]}
						<div>
							<div class="flex justify-between text-sm mb-1">
								<span class="font-medium">{year}</span>
								<span class="text-base-content/70">{formatNumber(points)}</span>
							</div>
							<div class="w-full bg-base-200 rounded-full h-3">
								<div
									class="bg-accent rounded-full h-3 transition-all duration-500"
									style="width: {(points / maxPoints()) * 100}%"
								></div>
							</div>
						</div>
					{/each}
				</div>

				<!-- By Category -->
				<div class="divider text-base-content/50 text-sm">By Category</div>
				<div class="space-y-3">
					{#each [
						{ key: 'flights', label: 'Flights', color: 'bg-primary' },
						{ key: 'hotels', label: 'Hotels', color: 'bg-secondary' },
						{ key: 'activities', label: 'Activities', color: 'bg-success' }
					] as cat}
						<div>
							<div class="flex justify-between text-sm mb-1">
								<span class="font-medium">{cat.label}</span>
								<span class="text-base-content/70">{formatNumber(stats.points_by_category[cat.key as keyof typeof stats.points_by_category])}</span>
							</div>
							<div class="w-full bg-base-200 rounded-full h-3">
								<div
									class="{cat.color} rounded-full h-3 transition-all duration-500"
									style="width: {(stats.points_by_category[cat.key as keyof typeof stats.points_by_category] / maxCategoryPoints()) * 100}%"
								></div>
							</div>
						</div>
					{/each}
				</div>
			</div>
		</div>
		<form method="dialog" class="modal-backdrop">
			<button>close</button>
		</form>
	</dialog>
{/if}
