<script lang="ts">
	/**
	 * Admin — Serverhelse-dashboard (oppgave 15.6)
	 *
	 * Viser tjeneste-status, system-metrikker (CPU, minne, disk),
	 * backup-status og logg-tilgang for alle tjenester i stacken.
	 */
	import { page } from '$app/stores';
	import {
		fetchHealthDashboard,
		fetchHealthLogs,
		type HealthDashboard,
		type LogsResponse
	} from '$lib/api';

	const session = $derived($page.data.session as Record<string, unknown> | undefined);
	const accessToken = $derived(session?.accessToken as string | undefined);

	let dashboard = $state<HealthDashboard | null>(null);
	let logs = $state<LogsResponse | null>(null);
	let error = $state<string | null>(null);
	let logsError = $state<string | null>(null);

	// Logg-filter
	let selectedService = $state<string>('');
	let logLines = $state(50);
	let showLogs = $state(false);

	// Poll dashboard hvert 10. sekund
	$effect(() => {
		if (!accessToken) return;
		loadDashboard();
		const interval = setInterval(loadDashboard, 10_000);
		return () => clearInterval(interval);
	});

	async function loadDashboard() {
		if (!accessToken) return;
		try {
			dashboard = await fetchHealthDashboard(accessToken);
			error = null;
		} catch (e) {
			error = String(e);
		}
	}

	async function loadLogs() {
		if (!accessToken) return;
		logsError = null;
		try {
			logs = await fetchHealthLogs(accessToken, {
				service: selectedService || undefined,
				lines: logLines
			});
		} catch (e) {
			logsError = String(e);
		}
	}

	function statusColor(status: string): string {
		if (status === 'up' || status === 'ok') return 'text-green-400';
		if (status === 'down' || status === 'missing') return 'text-red-400';
		if (status === 'degraded' || status === 'stale') return 'text-yellow-400';
		return 'text-neutral-400';
	}

	function statusDot(status: string): string {
		if (status === 'up') return 'bg-green-400';
		if (status === 'down') return 'bg-red-400';
		if (status === 'degraded') return 'bg-yellow-400';
		return 'bg-neutral-400';
	}

	function formatBytes(bytes: number): string {
		if (bytes === 0) return '0 B';
		const units = ['B', 'KB', 'MB', 'GB', 'TB'];
		const i = Math.floor(Math.log(bytes) / Math.log(1024));
		return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
	}

	function formatUptime(seconds: number): string {
		const days = Math.floor(seconds / 86400);
		const hours = Math.floor((seconds % 86400) / 3600);
		const mins = Math.floor((seconds % 3600) / 60);
		if (days > 0) return `${days}d ${hours}t ${mins}m`;
		if (hours > 0) return `${hours}t ${mins}m`;
		return `${mins}m`;
	}

	function logLevelColor(level: string): string {
		if (level === 'error') return 'text-red-400';
		if (level === 'warn') return 'text-yellow-400';
		if (level === 'info') return 'text-blue-400';
		return 'text-neutral-500';
	}

	const allServices = ['maskinrommet', 'caddy', 'postgres', 'authentik', 'litellm', 'whisper', 'livekit'];
</script>

<div class="min-h-screen bg-neutral-950 text-neutral-100 p-4 sm:p-8">
	<div class="max-w-6xl mx-auto space-y-6">
		<div class="flex items-center justify-between">
			<h1 class="text-2xl font-bold">Serverhelse</h1>
			<a href="/admin" class="text-sm text-neutral-400 hover:text-white">Tilbake til admin</a>
		</div>

		{#if error}
			<div class="bg-red-900/30 border border-red-700 rounded-lg p-4 text-red-300 text-sm">
				{error}
			</div>
		{/if}

		{#if !dashboard}
			<p class="text-neutral-500">Laster...</p>
		{:else}
			<!-- Tjeneste-status -->
			<section>
				<h2 class="text-lg font-semibold mb-3">Tjenester</h2>
				<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
					{#each dashboard.services as svc}
						<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
							<div class="flex items-center gap-2 mb-1">
								<span class="w-2.5 h-2.5 rounded-full {statusDot(svc.status)}"></span>
								<span class="font-medium">{svc.name}</span>
							</div>
							<div class="text-sm {statusColor(svc.status)} capitalize">{svc.status}</div>
							{#if svc.latency_ms !== null}
								<div class="text-xs text-neutral-500 mt-1">{svc.latency_ms} ms</div>
							{/if}
							{#if svc.details}
								<div class="text-xs text-neutral-600 mt-1 truncate" title={svc.details}>{svc.details}</div>
							{/if}
						</div>
					{/each}
				</div>
			</section>

			<!-- System-metrikker -->
			<section>
				<h2 class="text-lg font-semibold mb-3">System</h2>
				<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
					<!-- CPU -->
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400 mb-1">CPU</div>
						<div class="text-2xl font-mono">{dashboard.metrics.cpu_usage_percent.toFixed(0)}%</div>
						<div class="text-xs text-neutral-500 mt-1">
							{dashboard.metrics.cpu_cores} kjerner | Load: {dashboard.metrics.load_avg.map(v => v.toFixed(2)).join(', ')}
						</div>
					</div>

					<!-- Minne -->
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400 mb-1">Minne</div>
						<div class="text-2xl font-mono">{dashboard.metrics.memory_usage_percent.toFixed(0)}%</div>
						<div class="text-xs text-neutral-500 mt-1">
							{formatBytes(dashboard.metrics.memory_used_bytes)} / {formatBytes(dashboard.metrics.memory_total_bytes)}
						</div>
						<!-- Bar -->
						<div class="mt-2 h-1.5 bg-neutral-800 rounded-full overflow-hidden">
							<div
								class="h-full rounded-full transition-all {dashboard.metrics.memory_usage_percent > 90 ? 'bg-red-500' : dashboard.metrics.memory_usage_percent > 70 ? 'bg-yellow-500' : 'bg-green-500'}"
								style="width: {Math.min(dashboard.metrics.memory_usage_percent, 100)}%"
							></div>
						</div>
					</div>

					<!-- Disk -->
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400 mb-1">Disk</div>
						<div class="text-2xl font-mono">{dashboard.metrics.disk.usage_percent.toFixed(1)}%</div>
						<div class="text-xs text-neutral-500 mt-1">
							{formatBytes(dashboard.metrics.disk.used_bytes)} / {formatBytes(dashboard.metrics.disk.total_bytes)}
						</div>
						{#if dashboard.metrics.disk.alert_level}
							<div class="text-xs text-red-400 mt-1 uppercase">{dashboard.metrics.disk.alert_level}</div>
						{/if}
						<div class="mt-2 h-1.5 bg-neutral-800 rounded-full overflow-hidden">
							<div
								class="h-full rounded-full transition-all {dashboard.metrics.disk.usage_percent > 90 ? 'bg-red-500' : dashboard.metrics.disk.usage_percent > 80 ? 'bg-yellow-500' : 'bg-green-500'}"
								style="width: {Math.min(dashboard.metrics.disk.usage_percent, 100)}%"
							></div>
						</div>
					</div>

					<!-- Oppetid -->
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400 mb-1">Oppetid</div>
						<div class="text-2xl font-mono">{formatUptime(dashboard.metrics.uptime_seconds)}</div>
						<div class="text-xs text-neutral-500 mt-1">Siden siste reboot</div>
					</div>
				</div>
			</section>

			<!-- PG-statistikk -->
			<section>
				<h2 class="text-lg font-semibold mb-3">PostgreSQL</h2>
				<div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400">Tilkoblinger</div>
						<div class="text-xl font-mono">{dashboard.pg_stats.active_connections} / {dashboard.pg_stats.max_connections}</div>
					</div>
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400">DB-storrelse</div>
						<div class="text-xl font-mono">{formatBytes(dashboard.pg_stats.database_size_bytes)}</div>
					</div>
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400">Aktive sporringer</div>
						<div class="text-xl font-mono">{dashboard.pg_stats.active_queries}</div>
					</div>
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400">Frie tilkoblinger</div>
						<div class="text-xl font-mono">{dashboard.pg_stats.max_connections - dashboard.pg_stats.active_connections}</div>
					</div>
				</div>
			</section>

			<!-- Backup-status -->
			<section>
				<h2 class="text-lg font-semibold mb-3">Backup</h2>
				<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
					{#each dashboard.backups as backup}
						<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
							<div class="flex items-center gap-2">
								<span class="w-2 h-2 rounded-full {statusDot(backup.status === 'ok' ? 'up' : backup.status === 'stale' ? 'degraded' : 'down')}"></span>
								<span class="font-medium">{backup.backup_type}</span>
							</div>
							<div class="text-sm {statusColor(backup.status)} mt-1 capitalize">{backup.status}</div>
							{#if backup.last_success}
								<div class="text-xs text-neutral-500 mt-1">Siste: {new Date(backup.last_success).toLocaleString('nb-NO')}</div>
							{:else}
								<div class="text-xs text-neutral-500 mt-1">Ingen backup funnet</div>
							{/if}
						</div>
					{/each}
				</div>
			</section>

			<!-- Logg-tilgang -->
			<section>
				<div class="flex items-center justify-between mb-3">
					<h2 class="text-lg font-semibold">Logger</h2>
					<button
						class="text-sm text-neutral-400 hover:text-white"
						onclick={() => { showLogs = !showLogs; if (showLogs) loadLogs(); }}
					>
						{showLogs ? 'Skjul' : 'Vis logger'}
					</button>
				</div>

				{#if showLogs}
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4 space-y-3">
						<!-- Filtre -->
						<div class="flex flex-wrap gap-3 items-center">
							<select
								bind:value={selectedService}
								class="bg-neutral-800 border border-neutral-700 rounded px-3 py-1.5 text-sm"
								onchange={() => loadLogs()}
							>
								<option value="">Alle tjenester</option>
								{#each allServices as svc}
									<option value={svc}>{svc}</option>
								{/each}
							</select>
							<select
								bind:value={logLines}
								class="bg-neutral-800 border border-neutral-700 rounded px-3 py-1.5 text-sm"
								onchange={() => loadLogs()}
							>
								<option value={25}>25 linjer</option>
								<option value={50}>50 linjer</option>
								<option value={100}>100 linjer</option>
								<option value={200}>200 linjer</option>
							</select>
							<button
								class="bg-neutral-800 hover:bg-neutral-700 px-3 py-1.5 rounded text-sm"
								onclick={() => loadLogs()}
							>
								Oppdater
							</button>
						</div>

						{#if logsError}
							<div class="text-red-400 text-sm">{logsError}</div>
						{/if}

						{#if logs}
							<div class="max-h-96 overflow-y-auto font-mono text-xs space-y-0.5">
								{#each logs.entries as entry}
									<div class="flex gap-2 py-0.5 border-b border-neutral-800/50">
										<span class="text-neutral-600 shrink-0 w-40 truncate">{entry.timestamp}</span>
										<span class="text-neutral-500 shrink-0 w-24">{entry.service}</span>
										<span class="shrink-0 w-12 {logLevelColor(entry.level)}">{entry.level}</span>
										<span class="text-neutral-300 break-all">{entry.message}</span>
									</div>
								{/each}
								{#if logs.entries.length === 0}
									<div class="text-neutral-500 py-4 text-center">Ingen logger funnet</div>
								{/if}
							</div>
						{:else}
							<div class="text-neutral-500 text-sm">Laster logger...</div>
						{/if}
					</div>
				{/if}
			</section>
		{/if}
	</div>
</div>
