<script lang="ts">
	import {
		Users,
		DollarSign,
		Calendar,
		TrendingUp,
		TrendingDown,
		AlertCircle,
		Clock,
		Shield,
		Activity,
		FileText
	} from 'lucide-svelte';

	let { data } = $props();
	const { memberStats, revenueStats, upcomingEvents, recentPayments, auditLogs, overdueMembers } = data;

	// Calculate revenue trend
	const revenueTrend = revenueStats.lastMonth > 0
		? ((revenueStats.thisMonth - revenueStats.lastMonth) / revenueStats.lastMonth * 100).toFixed(1)
		: 0;
	const revenueUp = Number(revenueTrend) >= 0;

	function formatCurrency(amount: number): string {
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD'
		}).format(amount);
	}

	function formatDate(dateString: string): string {
		return new Date(dateString).toLocaleDateString('en-US', {
			month: 'short',
			day: 'numeric',
			year: 'numeric'
		});
	}

	function formatDateTime(dateString: string): string {
		return new Date(dateString).toLocaleString('en-US', {
			month: 'short',
			day: 'numeric',
			hour: 'numeric',
			minute: '2-digit'
		});
	}

	function formatAuditAction(action: string): string {
		const actionMap: Record<string, string> = {
			'member.create': 'Created member',
			'member.update': 'Updated member',
			'member.delete': 'Deleted member',
			'member.role_change': 'Changed role',
			'member.status_change': 'Changed status',
			'member.invite': 'Invited member',
			'event.create': 'Created event',
			'event.update': 'Updated event',
			'event.delete': 'Deleted event',
			'payment.record': 'Recorded payment',
			'document.upload': 'Uploaded document',
			'document.delete': 'Deleted document',
			'settings.update': 'Updated settings'
		};
		return actionMap[action] || action;
	}
</script>

<svelte:head>
	<title>Admin Dashboard | Monaco USA</title>
</svelte:head>

<div class="space-y-6">
	<!-- Page Header -->
	<div>
		<h1 class="text-2xl font-bold text-slate-900">Admin Dashboard</h1>
		<p class="text-slate-500">Overview of Monaco USA portal activity and metrics</p>
	</div>

	<!-- Stats Grid -->
	<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
		<!-- Total Members -->
		<div class="glass-card p-6">
			<div class="flex items-center justify-between">
				<div>
					<p class="text-sm text-slate-500">Total Members</p>
					<p class="mt-1 text-3xl font-bold text-slate-900">{memberStats.total}</p>
				</div>
				<div class="flex h-12 w-12 items-center justify-center rounded-full bg-blue-100">
					<Users class="h-6 w-6 text-blue-600" />
				</div>
			</div>
			<div class="mt-4 flex gap-2 text-xs">
				<span class="rounded bg-purple-100 px-2 py-0.5 text-purple-700">{memberStats.byRole.admin} Admin</span>
				<span class="rounded bg-indigo-100 px-2 py-0.5 text-indigo-700">{memberStats.byRole.board} Board</span>
				<span class="rounded bg-slate-100 px-2 py-0.5 text-slate-700">{memberStats.byRole.member} Members</span>
			</div>
		</div>

		<!-- Revenue This Month -->
		<div class="glass-card p-6">
			<div class="flex items-center justify-between">
				<div>
					<p class="text-sm text-slate-500">Revenue This Month</p>
					<p class="mt-1 text-3xl font-bold text-slate-900">{formatCurrency(revenueStats.thisMonth)}</p>
				</div>
				<div class="flex h-12 w-12 items-center justify-center rounded-full bg-green-100">
					<DollarSign class="h-6 w-6 text-green-600" />
				</div>
			</div>
			<div class="mt-4 flex items-center gap-1 text-sm">
				{#if revenueUp}
					<TrendingUp class="h-4 w-4 text-green-600" />
					<span class="text-green-600">+{revenueTrend}%</span>
				{:else}
					<TrendingDown class="h-4 w-4 text-red-600" />
					<span class="text-red-600">{revenueTrend}%</span>
				{/if}
				<span class="text-slate-500">vs last month</span>
			</div>
		</div>

		<!-- Dues Status -->
		<div class="glass-card p-6">
			<div class="flex items-center justify-between">
				<div>
					<p class="text-sm text-slate-500">Dues Status</p>
					<p class="mt-1 text-3xl font-bold text-green-600">{memberStats.byDuesStatus.current}</p>
				</div>
				<div class="flex h-12 w-12 items-center justify-center rounded-full bg-amber-100">
					<AlertCircle class="h-6 w-6 text-amber-600" />
				</div>
			</div>
			<div class="mt-4 flex gap-2 text-xs">
				<span class="rounded bg-green-100 px-2 py-0.5 text-green-700">Current</span>
				<span class="rounded bg-amber-100 px-2 py-0.5 text-amber-700">{memberStats.byDuesStatus.due_soon} Due Soon</span>
				<span class="rounded bg-red-100 px-2 py-0.5 text-red-700">{memberStats.byDuesStatus.overdue} Overdue</span>
			</div>
		</div>

		<!-- Upcoming Events -->
		<div class="glass-card p-6">
			<div class="flex items-center justify-between">
				<div>
					<p class="text-sm text-slate-500">Upcoming Events</p>
					<p class="mt-1 text-3xl font-bold text-slate-900">{upcomingEvents.length}</p>
				</div>
				<div class="flex h-12 w-12 items-center justify-center rounded-full bg-monaco-100">
					<Calendar class="h-6 w-6 text-monaco-600" />
				</div>
			</div>
			<p class="mt-4 text-sm text-slate-500">Next 30 days</p>
		</div>
	</div>

	<!-- Main Content Grid -->
	<div class="grid gap-6 lg:grid-cols-2">
		<!-- Recent Payments -->
		<div class="glass-card p-6">
			<div class="mb-4 flex items-center justify-between">
				<h2 class="font-semibold text-slate-900">Recent Payments</h2>
				<a href="/board/dues" class="text-sm text-monaco-600 hover:underline">View all</a>
			</div>

			{#if recentPayments.length > 0}
				<div class="space-y-3">
					{#each recentPayments as payment}
						<div class="flex items-center justify-between rounded-lg bg-slate-50/50 p-3">
							<div>
								<p class="font-medium text-slate-900">
									{payment.member?.first_name} {payment.member?.last_name}
								</p>
								<p class="text-xs text-slate-500">{formatDate(payment.payment_date)}</p>
							</div>
							<span class="font-semibold text-green-600">{formatCurrency(payment.amount)}</span>
						</div>
					{/each}
				</div>
			{:else}
				<p class="text-center text-slate-500">No recent payments</p>
			{/if}
		</div>

		<!-- Upcoming Events -->
		<div class="glass-card p-6">
			<div class="mb-4 flex items-center justify-between">
				<h2 class="font-semibold text-slate-900">Upcoming Events</h2>
				<a href="/board/events" class="text-sm text-monaco-600 hover:underline">View all</a>
			</div>

			{#if upcomingEvents.length > 0}
				<div class="space-y-3">
					{#each upcomingEvents as event}
						<div class="flex items-center justify-between rounded-lg bg-slate-50/50 p-3">
							<div>
								<p class="font-medium text-slate-900">{event.title}</p>
								<p class="text-xs text-slate-500">
									{formatDateTime(event.start_datetime)}
									{#if event.location}
										 | {event.location}
									{/if}
								</p>
							</div>
							<div class="text-right">
								<span class="text-sm font-medium text-slate-900">{event.total_attendees}</span>
								{#if event.max_attendees}
									<span class="text-slate-500">/{event.max_attendees}</span>
								{/if}
								<p class="text-xs text-slate-500">attendees</p>
							</div>
						</div>
					{/each}
				</div>
			{:else}
				<p class="text-center text-slate-500">No upcoming events</p>
			{/if}
		</div>

		<!-- Overdue Members -->
		<div class="glass-card p-6">
			<div class="mb-4 flex items-center justify-between">
				<h2 class="font-semibold text-slate-900">Overdue Dues</h2>
				<a href="/board/dues?status=overdue" class="text-sm text-monaco-600 hover:underline">View all</a>
			</div>

			{#if overdueMembers.length > 0}
				<div class="space-y-3">
					{#each overdueMembers as member}
						<div class="flex items-center justify-between rounded-lg bg-red-50/50 p-3">
							<div>
								<p class="font-medium text-slate-900">
									{member.first_name} {member.last_name}
								</p>
								<p class="text-xs text-slate-500">{member.email}</p>
							</div>
							<div class="text-right">
								<span class="text-sm font-medium text-red-600">
									{member.days_overdue} days
								</span>
								<p class="text-xs text-slate-500">overdue</p>
							</div>
						</div>
					{/each}
				</div>
			{:else}
				<div class="flex flex-col items-center justify-center py-8 text-slate-500">
					<Shield class="mb-2 h-8 w-8" />
					<p>All members are current!</p>
				</div>
			{/if}
		</div>

		<!-- Recent Activity (Audit Log) -->
		<div class="glass-card p-6">
			<div class="mb-4 flex items-center justify-between">
				<h2 class="font-semibold text-slate-900">Recent Activity</h2>
				<Activity class="h-5 w-5 text-slate-400" />
			</div>

			{#if auditLogs.length > 0}
				<div class="space-y-3">
					{#each auditLogs.slice(0, 8) as log}
						<div class="flex items-start gap-3 text-sm">
							<div class="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-slate-100">
								{#if log.action.startsWith('member')}
									<Users class="h-3 w-3 text-slate-500" />
								{:else if log.action.startsWith('event')}
									<Calendar class="h-3 w-3 text-slate-500" />
								{:else if log.action.startsWith('payment')}
									<DollarSign class="h-3 w-3 text-slate-500" />
								{:else if log.action.startsWith('document')}
									<FileText class="h-3 w-3 text-slate-500" />
								{:else}
									<Clock class="h-3 w-3 text-slate-500" />
								{/if}
							</div>
							<div class="flex-1 min-w-0">
								<p class="text-slate-900 truncate">
									{formatAuditAction(log.action)}
									{#if log.details?.target_email}
										<span class="text-slate-500">({log.details.target_email})</span>
									{/if}
								</p>
								<p class="text-xs text-slate-500">
									{log.user_email || 'System'} · {formatDateTime(log.created_at)}
								</p>
							</div>
						</div>
					{/each}
				</div>
			{:else}
				<p class="text-center text-slate-500">No recent activity</p>
			{/if}
		</div>
	</div>
</div>
