<script lang="ts">
	/**
	 * Admin — Brukeradministrasjon (oppgave 064)
	 *
	 * Viser person-noder med roller, AI-budsjett, siste aktivitet.
	 * Støtter deaktivering/aktivering og oppdatering av AI-budsjett.
	 */
	import { page } from '$app/stores';
	import {
		fetchUsersOverview,
		toggleUser,
		updateUserBudget,
		type UsersOverviewResponse,
		type UserInfo
	} 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<UsersOverviewResponse | null>(null);
	let error = $state<string | null>(null);
	let actionLoading = $state<string | null>(null);

	// Budsjett-redigering
	let editingBudget = $state<string | null>(null);
	let budgetInput = $state('');

	// Filter
	let filter = $state('');

	const filteredUsers = $derived(
		data?.users.filter((u) => {
			if (!filter) return true;
			const q = filter.toLowerCase();
			return (
				u.title.toLowerCase().includes(q) ||
				(u.email?.toLowerCase().includes(q) ?? false) ||
				u.roles.some((r) => r.collection_title.toLowerCase().includes(q))
			);
		}) ?? []
	);

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

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

	async function handleToggle(nodeId: string, title: string, isActive: boolean) {
		if (!accessToken || actionLoading) return;
		const action = isActive ? 'deaktivere' : 'aktivere';
		if (!confirm(`Vil du ${action} brukeren «${title}»?`)) return;
		actionLoading = nodeId;
		try {
			await toggleUser(accessToken, nodeId);
			await loadData();
		} catch (e) {
			error = String(e);
		} finally {
			actionLoading = null;
		}
	}

	function startEditBudget(user: UserInfo) {
		editingBudget = user.node_id;
		budgetInput = user.ai_budget?.monthly_limit_usd?.toString() ?? '';
	}

	async function saveBudget(nodeId: string) {
		if (!accessToken || actionLoading) return;
		actionLoading = nodeId;
		try {
			const limit = budgetInput.trim() === '' ? null : parseFloat(budgetInput);
			if (limit !== null && (isNaN(limit) || limit < 0)) {
				error = 'Ugyldig budsjettverdi';
				return;
			}
			await updateUserBudget(accessToken, nodeId, limit);
			editingBudget = null;
			budgetInput = '';
			await loadData();
		} catch (e) {
			error = String(e);
		} finally {
			actionLoading = null;
		}
	}

	function cancelEditBudget() {
		editingBudget = null;
		budgetInput = '';
	}

	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'
		});
	}

	function timeAgo(iso: string | null): string {
		if (!iso) return 'Aldri';
		const diff = Date.now() - new Date(iso).getTime();
		const minutes = Math.floor(diff / 60000);
		if (minutes < 1) return 'Akkurat nå';
		if (minutes < 60) return `${minutes}m siden`;
		const hours = Math.floor(minutes / 60);
		if (hours < 24) return `${hours}t siden`;
		const days = Math.floor(hours / 24);
		if (days < 30) return `${days}d siden`;
		return formatTime(iso);
	}

	function roleLabel(role: string): string {
		switch (role) {
			case 'owner':
				return 'Eier';
			case 'admin':
				return 'Admin';
			case 'member_of':
				return 'Medlem';
			default:
				return role;
		}
	}

	function roleColor(role: string): string {
		switch (role) {
			case 'owner':
				return 'bg-purple-100 text-purple-700';
			case 'admin':
				return 'bg-blue-100 text-blue-700';
			case 'member_of':
				return 'bg-gray-100 text-gray-700';
			default:
				return 'bg-gray-100 text-gray-600';
		}
	}

	function budgetStatus(user: UserInfo): string {
		if (!user.ai_budget) return '';
		const pct = (user.ai_usage_this_month / user.ai_budget.monthly_limit_usd) * 100;
		if (pct >= 100) return 'bg-red-100 text-red-700';
		if (pct >= 80) return 'bg-amber-100 text-amber-700';
		return 'bg-green-100 text-green-700';
	}
</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">Brukere</h1>
			</div>
			{#if data}
				<span class="text-sm text-gray-400">{data.total_count} brukere</span>
			{/if}
		</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 brukere...</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}
					<button onclick={() => (error = null)} class="ml-2 underline">Lukk</button>
				</div>
			{/if}

			<!-- Søkefilter -->
			<div class="mb-4">
				<input
					type="text"
					placeholder="Filtrer brukere..."
					bind:value={filter}
					class="w-full rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm focus:border-blue-300 focus:outline-none focus:ring-1 focus:ring-blue-300 sm:w-64"
				/>
			</div>

			<!-- Brukerliste -->
			<section class="space-y-3">
				{#each filteredUsers as user (user.node_id)}
					<div
						class="rounded-lg border bg-white p-4 shadow-sm {user.is_active ? 'border-gray-200' : 'border-red-200 bg-red-50/30'}"
					>
						<div class="flex flex-wrap items-start justify-between gap-3">
							<!-- Brukerinfo -->
							<div class="min-w-0 flex-1">
								<div class="flex items-center gap-2">
									<span class="font-medium text-gray-900">{user.title}</span>
									{#if user.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-3 text-xs text-gray-500">
									{#if user.email}
										<span>{user.email}</span>
									{/if}
									<span>Opprettet: {formatTime(user.created_at)}</span>
									<span>Siste aktivitet: {timeAgo(user.last_activity)}</span>
								</div>
								<div
									class="mt-1 font-mono text-xs text-gray-400"
									title={user.node_id}
								>
									{user.node_id}
								</div>
							</div>

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

						<!-- Roller og budsjett -->
						<div class="mt-3 flex flex-wrap gap-4">
							<!-- Roller -->
							<div class="flex-1">
								<div class="mb-1 text-xs font-medium text-gray-500">Roller</div>
								{#if user.roles.length > 0}
									<div class="flex flex-wrap gap-1">
										{#each user.roles as role}
											<span
												class="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium {roleColor(role.role)}"
											>
												{roleLabel(role.role)} i {role.collection_title}
											</span>
										{/each}
									</div>
								{:else}
									<span class="text-xs text-gray-400">Ingen roller</span>
								{/if}
							</div>

							<!-- AI-budsjett -->
							<div class="min-w-[180px]">
								<div class="mb-1 text-xs font-medium text-gray-500">AI-budsjett</div>
								{#if editingBudget === user.node_id}
									<div class="flex items-center gap-1">
										<span class="text-xs text-gray-500">$</span>
										<input
											type="number"
											step="1"
											min="0"
											bind:value={budgetInput}
											placeholder="Ingen grense"
											class="w-20 rounded border border-gray-300 px-2 py-1 text-xs focus:border-blue-300 focus:outline-none"
											onkeydown={(e: KeyboardEvent) => {
												if (e.key === 'Enter') saveBudget(user.node_id);
												if (e.key === 'Escape') cancelEditBudget();
											}}
										/>
										<span class="text-xs text-gray-400">/mnd</span>
										<button
											onclick={() => saveBudget(user.node_id)}
											disabled={actionLoading === user.node_id}
											class="rounded bg-blue-50 px-2 py-1 text-xs text-blue-700 hover:bg-blue-100 disabled:opacity-50"
										>
											Lagre
										</button>
										<button
											onclick={cancelEditBudget}
											class="rounded px-2 py-1 text-xs text-gray-500 hover:bg-gray-100"
										>
											Avbryt
										</button>
									</div>
								{:else}
									<div class="flex items-center gap-2">
										{#if user.ai_budget}
											<span
												class="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium {budgetStatus(user)}"
											>
												${user.ai_usage_this_month.toFixed(2)} / ${user.ai_budget.monthly_limit_usd.toFixed(0)}
											</span>
										{:else}
											<span class="text-xs text-gray-400">
												{#if user.ai_usage_this_month > 0}
													${user.ai_usage_this_month.toFixed(2)} (ingen grense)
												{:else}
													Ingen grense
												{/if}
											</span>
										{/if}
										<button
											onclick={() => startEditBudget(user)}
											class="rounded px-1.5 py-0.5 text-xs text-gray-400 hover:bg-gray-100 hover:text-gray-600"
										>
											Endre
										</button>
									</div>
								{/if}
							</div>
						</div>
					</div>
				{:else}
					<div
						class="rounded-lg border border-gray-200 bg-white p-6 text-center text-sm text-gray-400"
					>
						{#if filter}
							Ingen brukere matcher filteret.
						{:else}
							Ingen brukere funnet.
						{/if}
					</div>
				{/each}
			</section>
		{/if}
	</main>
</div>
