<script lang="ts">
	import { goto } from '$app/navigation';
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import { AdminDashboardHeader } from '$lib/components/admin';
	import type { Event } from '$lib/graphql/queries/events';

	let { data }: { data: PageData } = $props();

	let events = $derived(data.events as Event[]);
	let limit = $derived(data.limit);
	let offset = $derived(data.offset);

	// Filter state
	let entityTypeFilter = $state('');
	let eventTypeFilter = $state('');

	// Get unique entity types for filter dropdown
	let entityTypes = $derived([...new Set(events.map((e) => e.entityType))].sort());
	let eventTypes = $derived([...new Set(events.map((e) => e.eventType))].sort());

	// Filtered events
	let filteredEvents = $derived(
		events.filter((e) => {
			if (entityTypeFilter && e.entityType !== entityTypeFilter) return false;
			if (eventTypeFilter && e.eventType !== eventTypeFilter) return false;
			return true;
		})
	);

	function formatRelativeTime(dateStr: string): string {
		const date = new Date(dateStr);
		const now = new Date();
		const diffMs = now.getTime() - date.getTime();
		const diffSecs = Math.floor(diffMs / 1000);
		const diffMins = Math.floor(diffSecs / 60);
		const diffHours = Math.floor(diffMins / 60);
		const diffDays = Math.floor(diffHours / 24);

		if (diffSecs < 60) return 'Just now';
		if (diffMins < 60) return `${diffMins}m ago`;
		if (diffHours < 24) return `${diffHours}h ago`;
		if (diffDays < 7) return `${diffDays}d ago`;
		return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
	}

	function formatEventType(eventType: string): string {
		// Convert PascalCase to Title Case with spaces
		return eventType.replace(/([A-Z])/g, ' $1').trim();
	}

	function getEventTypeColor(eventType: string): string {
		if (eventType.includes('Created'))
			return 'bg-success-100 text-success-800 dark:bg-success-900/30 dark:text-success-400';
		if (eventType.includes('Deleted'))
			return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
		if (eventType.includes('Started'))
			return 'bg-accent-100 text-accent-800 dark:bg-accent-900/30 dark:text-accent-400';
		if (eventType.includes('Ended') || eventType.includes('Completed'))
			return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400';
		if (eventType.includes('Changed'))
			return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
		if (eventType.includes('Sent') || eventType.includes('Paid'))
			return 'bg-accent2-100 text-accent2-800 dark:bg-accent2-900/30 dark:text-accent2-400';
		return 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300';
	}

	function getEntityTypeColor(entityType: string): string {
		switch (entityType) {
			case 'service':
			case 'service_session':
				return 'bg-secondary-100 text-secondary-800 dark:bg-secondary-900/30 dark:text-secondary-400';
			case 'project':
			case 'project_session':
				return 'bg-accent-100 text-accent-800 dark:bg-accent-900/30 dark:text-accent-400';
			case 'invoice':
				return 'bg-accent6-100 text-accent6-800 dark:bg-accent6-900/30 dark:text-accent6-400';
			case 'customer':
				return 'bg-accent3-100 text-accent3-800 dark:bg-accent3-900/30 dark:text-accent3-400';
			case 'account':
				return 'bg-primary-100 text-primary-800 dark:bg-primary-900/30 dark:text-primary-400';
			case 'team_profile':
			case 'customer_profile':
				return 'bg-accent4-100 text-accent4-800 dark:bg-accent4-900/30 dark:text-accent4-400';
			case 'report':
				return 'bg-accent2-100 text-accent2-800 dark:bg-accent2-900/30 dark:text-accent2-400';
			default:
				return 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300';
		}
	}

	function loadMore() {
		goto(`/admin/events?limit=${limit}&offset=${offset + limit}`);
	}

	function loadPrevious() {
		const newOffset = Math.max(0, offset - limit);
		goto(`/admin/events?limit=${limit}&offset=${newOffset}`);
	}
</script>

<svelte:head>
	<title>Event Log - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<AdminDashboardHeader title="Event Log">
			{#snippet subtitleSnippet()}
				System audit trail - {filteredEvents.length} event{filteredEvents.length !== 1 ? 's' : ''}
				{#if offset > 0}
					(showing {offset + 1} - {offset + events.length})
				{/if}
			{/snippet}
		</AdminDashboardHeader>

		<!-- Filters -->
		<div class="mb-6 flex flex-wrap gap-4">
			<label class="flex items-center gap-2">
				<span class="text-sm font-medium text-theme">Entity Type:</span>
				<select
					bind:value={entityTypeFilter}
					class="rounded-lg border border-theme bg-theme px-3 py-1.5 text-sm text-theme"
				>
					<option value="">All</option>
					{#each entityTypes as type}
						<option value={type}>{type.replace(/_/g, ' ')}</option>
					{/each}
				</select>
			</label>

			<label class="flex items-center gap-2">
				<span class="text-sm font-medium text-theme">Event Type:</span>
				<select
					bind:value={eventTypeFilter}
					class="rounded-lg border border-theme bg-theme px-3 py-1.5 text-sm text-theme"
				>
					<option value="">All</option>
					{#each eventTypes as type}
						<option value={type}>{formatEventType(type)}</option>
					{/each}
				</select>
			</label>

			{#if entityTypeFilter || eventTypeFilter}
				<button
					type="button"
					class="text-sm text-accent-600 hover:text-accent-700 dark:text-accent-400 dark:hover:text-accent-300"
					onclick={() => {
						entityTypeFilter = '';
						eventTypeFilter = '';
					}}
				>
					Clear filters
				</button>
			{/if}
		</div>

		<!-- Events List -->
		{#if filteredEvents.length > 0}
			<div class="space-y-2">
				{#each filteredEvents as event (event.id)}
					<div class="rounded-lg border border-theme bg-theme-card p-4">
						<div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
							<div class="min-w-0 flex-1">
								<!-- Event description -->
								<p class="font-medium text-theme">{event.description}</p>

								<!-- Tags -->
								<div class="mt-2 flex flex-wrap items-center gap-2">
									<span
										class="rounded px-2 py-0.5 text-xs font-medium {getEventTypeColor(
											event.eventType
										)}"
									>
										{formatEventType(event.eventType)}
									</span>
									<span
										class="rounded px-2 py-0.5 text-xs font-medium {getEntityTypeColor(
											event.entityType
										)}"
									>
										{event.entityType.replace(/_/g, ' ')}
									</span>
								</div>

								<!-- Metadata preview -->
								{#if event.metadata && Object.keys(event.metadata).length > 0}
									<div class="mt-2 text-xs text-theme-muted">
										{#each Object.entries(event.metadata).slice(0, 3) as [key, value]}
											<span class="mr-3">
												<span class="font-medium">{key}:</span>
												{typeof value === 'string' ? value : JSON.stringify(value)}
											</span>
										{/each}
										{#if Object.keys(event.metadata).length > 3}
											<span class="text-theme-muted"
												>+{Object.keys(event.metadata).length - 3} more</span
											>
										{/if}
									</div>
								{/if}
							</div>

							<!-- Right side: actor and timestamp -->
							<div class="shrink-0 text-right text-sm">
								{#if event.actorProfile}
									<p class="font-medium text-theme">{event.actorProfile.fullName}</p>
								{:else if event.actorType === 'system'}
									<p class="font-medium text-theme-secondary">System</p>
								{/if}
								<p class="text-theme-muted">{formatRelativeTime(event.timestamp)}</p>
							</div>
						</div>
					</div>
				{/each}
			</div>

			<!-- Pagination -->
			<div class="mt-6 flex items-center justify-between">
				<button type="button" class="btn-secondary" disabled={offset === 0} onclick={loadPrevious}>
					Previous
				</button>
				<span class="text-sm text-theme-muted">
					Showing {offset + 1} - {offset + events.length}
				</span>
				<button
					type="button"
					class="btn-secondary"
					disabled={events.length < limit}
					onclick={loadMore}
				>
					Next
				</button>
			</div>
		{:else}
			<!-- Empty state -->
			<div class="rounded-lg border border-dashed border-theme py-12 text-center">
				<svg
					class="mx-auto h-12 w-12 text-theme-muted"
					fill="none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"
					/>
				</svg>
				<h3 class="mt-4 text-lg font-medium text-theme">No events yet</h3>
				<p class="mt-2 text-theme-secondary">System events will appear here as they occur.</p>
			</div>
		{/if}
	</ContentContainer>
</div>
