<script lang="ts">
	/**
	 * Admin — Agent-oversikt (oppgave 063)
	 *
	 * Viser registrerte agenter med status, token-forbruk, aktive jobber
	 * og kjørehistorikk. Støtter kill switch (aktiver/deaktiver).
	 */
	import { page } from '$app/stores';
	import {
		fetchAgentsOverview,
		toggleAgent,
		type AgentsOverviewResponse,
		type AgentDetail,
		type AgentHistoryEntry
	} from '$lib/api';

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

	let data = $state<AgentsOverviewResponse | null>(null);
	let loading = $state(false);
	let error = $state<string | null>(null);
	let actionLoading = $state<string | null>(null);

	// Poll hvert 5. sekund
	$effect(() => {
		if (!accessToken) return;
		loadData();
		const interval = setInterval(loadData, 5000);
		return () => clearInterval(interval);
	});

	async function loadData() {
		if (!accessToken) return;
		try {
			data = await fetchAgentsOverview(accessToken);
			error = null;
		} catch (e) {
			error = String(e);
		}
	}

	async function handleToggle(nodeId: string) {
		if (!accessToken || actionLoading) return;
		actionLoading = nodeId;
		try {
			await toggleAgent(accessToken, nodeId);
			await loadData();
		} catch (e) {
			error = String(e);
		} finally {
			actionLoading = null;
		}
	}

	function formatTime(iso: string | null): string {
		if (!iso) return '-';
		return new Date(iso).toLocaleString('nb-NO', {
			day: '2-digit', month: '2-digit',
			hour: '2-digit', minute: '2-digit', second: '2-digit'
		});
	}

	function formatDuration(ms: number | null): string {
		if (ms === null) return '-';
		if (ms < 1000) return `${ms}ms`;
		const s = Math.round(ms / 1000);
		if (s < 60) return `${s}s`;
		const m = Math.floor(s / 60);
		return `${m}m ${s % 60}s`;
	}

	function formatTokens(n: number): string {
		if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
		if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
		return String(n);
	}

	function modelAlias(agent: AgentDetail): string {
		return (agent.agent.config?.model_alias as string) ?? 'ukjent';
	}

	function rateLimit(agent: AgentDetail): number {
		return (agent.agent.config?.rate_limit_per_hour as number) ?? 60;
	}

	function statusColor(status: string): string {
		switch (status) {
			case 'running': return 'bg-blue-100 text-blue-700';
			case 'pending': return 'bg-yellow-100 text-yellow-700';
			case 'completed': return 'bg-green-100 text-green-700';
			case 'error': return 'bg-red-100 text-red-700';
			case 'retry': return 'bg-amber-100 text-amber-700';
			default: return 'bg-gray-100 text-gray-700';
		}
	}

	function statusDot(status: string): string {
		switch (status) {
			case 'running': return 'bg-blue-500';
			case 'pending': return 'bg-yellow-500';
			case 'completed': return 'bg-green-500';
			case 'error': return 'bg-red-500';
			case 'retry': return 'bg-amber-500';
			default: return 'bg-gray-500';
		}
	}

	function resultStatusLabel(entry: AgentHistoryEntry): string {
		if (entry.status === 'error') return entry.error_msg?.slice(0, 60) ?? 'Feil';
		if (entry.result_status === 'skipped') return 'Hoppet over';
		if (entry.result_status === 'ok' || entry.status === 'completed') return 'OK';
		return entry.result_status ?? entry.status;
	}
</script>

<div class="min-h-screen bg-gray-50">
	<header class="border-b border-gray-200 bg-white">
		<div class="mx-auto flex max-w-5xl items-center justify-between px-4 py-3">
			<div class="flex items-center gap-3">
				<a href="/admin" class="text-sm text-gray-500 hover:text-gray-700">Admin</a>
				<span class="text-gray-300">/</span>
				<h1 class="text-lg font-semibold text-gray-900">Agenter</h1>
			</div>
		</div>
	</header>

	<main class="mx-auto max-w-5xl px-4 py-6">
		{#if !accessToken}
			<p class="text-sm text-gray-400">Logg inn for tilgang.</p>
		{:else if !data}
			<p class="text-sm text-gray-400">Laster agenter...</p>
		{:else}
			<!-- Feilmelding -->
			{#if error}
				<div class="mb-4 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">
					{error}
				</div>
			{/if}

			<!-- Agent-kort -->
			<section class="mb-8 space-y-4">
				<h2 class="text-sm font-medium text-gray-600">Registrerte agenter</h2>
				{#each data.agents as detail (detail.agent.node_id)}
					<div class="rounded-lg border border-gray-200 bg-white p-4 shadow-sm">
						<div class="flex flex-wrap items-start justify-between gap-3">
							<!-- Agent-info -->
							<div class="min-w-0 flex-1">
								<div class="flex items-center gap-2">
									<span class="font-mono text-sm font-semibold text-gray-900">
										{detail.agent.agent_key}
									</span>
									{#if detail.agent.is_active}
										<span class="inline-flex items-center gap-1 rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700">
											<span class="h-1.5 w-1.5 rounded-full bg-green-500"></span>
											Aktiv
										</span>
									{:else}
										<span class="inline-flex items-center gap-1 rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700">
											<span class="h-1.5 w-1.5 rounded-full bg-red-500"></span>
											Deaktivert
										</span>
									{/if}
								</div>
								<div class="mt-1 flex flex-wrap gap-4 text-xs text-gray-500">
									<span>Type: <span class="font-medium text-gray-700">{detail.agent.agent_type}</span></span>
									<span>Modell: <span class="font-medium text-gray-700">{modelAlias(detail)}</span></span>
									<span>Rate: <span class="font-medium text-gray-700">{detail.usage.usage_last_hour}/{rateLimit(detail)} per time</span></span>
								</div>
								<div class="mt-1 font-mono text-xs text-gray-400" title={detail.agent.node_id}>
									{detail.agent.node_id}
								</div>
							</div>

							<!-- Kill switch -->
							<button
								onclick={() => handleToggle(detail.agent.node_id)}
								disabled={actionLoading === detail.agent.node_id}
								class="shrink-0 rounded px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50 {detail.agent.is_active ? 'bg-red-50 text-red-700 hover:bg-red-100' : 'bg-green-50 text-green-700 hover:bg-green-100'}"
							>
								{detail.agent.is_active ? 'Deaktiver' : 'Aktiver'}
							</button>
						</div>

						<!-- Statistikk -->
						<div class="mt-3 grid grid-cols-2 gap-3 sm:grid-cols-4">
							<div class="rounded border border-gray-100 bg-gray-50 p-2 text-center">
								<div class="text-lg font-bold text-gray-900">{detail.usage.usage_last_hour}</div>
								<div class="text-xs text-gray-500">Siste time</div>
							</div>
							<div class="rounded border border-gray-100 bg-gray-50 p-2 text-center">
								<div class="text-lg font-bold text-gray-900">{detail.usage.usage_last_24h}</div>
								<div class="text-xs text-gray-500">Siste 24t</div>
							</div>
							<div class="rounded border border-gray-100 bg-gray-50 p-2 text-center">
								<div class="text-lg font-bold text-gray-900">{formatTokens(detail.usage.tokens_last_24h.prompt_tokens + detail.usage.tokens_last_24h.completion_tokens)}</div>
								<div class="text-xs text-gray-500">Tokens 24t</div>
							</div>
							<div class="rounded border border-gray-100 bg-gray-50 p-2 text-center">
								<div class="text-lg font-bold text-gray-900">{detail.usage.usage_total}</div>
								<div class="text-xs text-gray-500">Totalt</div>
							</div>
						</div>

						<!-- Token-detaljer 24t -->
						{#if detail.usage.tokens_last_24h.prompt_tokens > 0 || detail.usage.tokens_last_24h.completion_tokens > 0}
							<div class="mt-2 flex flex-wrap gap-4 text-xs text-gray-500">
								<span>Inn: {formatTokens(detail.usage.tokens_last_24h.prompt_tokens)}</span>
								<span>Ut: {formatTokens(detail.usage.tokens_last_24h.completion_tokens)}</span>
								{#if detail.usage.tokens_last_24h.estimated_cost > 0}
									<span>Kostnad: ${detail.usage.tokens_last_24h.estimated_cost.toFixed(4)}</span>
								{/if}
							</div>
						{/if}

						<!-- Aktive jobber -->
						{#if detail.current_jobs.length > 0}
							<div class="mt-3 rounded border border-blue-100 bg-blue-50 p-2">
								<div class="mb-1 text-xs font-medium text-blue-700">Aktive jobber</div>
								{#each detail.current_jobs as job}
									<div class="flex items-center gap-2 text-xs text-blue-600">
										<span class="inline-flex items-center gap-1 rounded-full {statusColor(job.status)} px-1.5 py-0.5 text-xs">
											<span class="h-1 w-1 rounded-full {statusDot(job.status)}"></span>
											{job.status}
										</span>
										<span class="font-mono">{job.job_id.slice(0, 8)}</span>
										{#if job.started_at}
											<span class="text-blue-400">{formatTime(job.started_at)}</span>
										{/if}
									</div>
								{/each}
							</div>
						{/if}
					</div>
				{:else}
					<div class="rounded-lg border border-gray-200 bg-white p-6 text-center text-sm text-gray-400">
						Ingen agenter registrert.
					</div>
				{/each}
			</section>

			<!-- Historikk -->
			<section>
				<h2 class="mb-3 text-sm font-medium text-gray-600">Siste kjøringer</h2>
				<div class="overflow-x-auto rounded-lg border border-gray-200 bg-white shadow-sm">
					<table class="w-full text-sm">
						<thead>
							<tr class="border-b border-gray-100 bg-gray-50 text-left text-xs font-medium text-gray-500">
								<th class="px-3 py-2">Status</th>
								<th class="px-3 py-2">Jobb</th>
								<th class="px-3 py-2">Startet</th>
								<th class="px-3 py-2">Varighet</th>
								<th class="px-3 py-2">Resultat</th>
							</tr>
						</thead>
						<tbody>
							{#each data.history as entry (entry.job_id)}
								<tr class="border-b border-gray-50 hover:bg-gray-50">
									<td class="px-3 py-2">
										<span class="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium {statusColor(entry.status)}">
											<span class="h-1.5 w-1.5 rounded-full {statusDot(entry.status)}"></span>
											{entry.status}
										</span>
									</td>
									<td class="px-3 py-2 font-mono text-xs text-gray-500" title={entry.job_id}>
										{entry.job_id.slice(0, 8)}
									</td>
									<td class="px-3 py-2 text-xs text-gray-400">
										{formatTime(entry.started_at)}
									</td>
									<td class="px-3 py-2 text-xs text-gray-500">
										{formatDuration(entry.duration_ms)}
									</td>
									<td class="max-w-[200px] truncate px-3 py-2 text-xs {entry.status === 'error' ? 'text-red-600' : 'text-gray-600'}" title={entry.error_msg ?? entry.result_status ?? ''}>
										{resultStatusLabel(entry)}
									</td>
								</tr>
							{:else}
								<tr>
									<td colspan="5" class="px-3 py-8 text-center text-sm text-gray-400">
										Ingen agent-kjøringer funnet.
									</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</section>
		{/if}
	</main>
</div>
