<script lang="ts">
	/**
	 * Admin — API-nøkler (oppgave 060)
	 *
	 * Administrer krypterte API-nøkler for tredjepartstjenester.
	 * Nøkler lagres kryptert i PG, kun hint vises etter lagring.
	 */
	import { page } from '$app/stores';
	import {
		fetchApiKeys,
		createApiKey,
		testApiKey,
		deactivateApiKey,
		deleteApiKey,
		type ApiKeyInfo,
		type TestKeyResponse
	} from '$lib/api';

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

	let keys = $state<ApiKeyInfo[]>([]);
	let loading = $state(false);
	let error = $state<string | null>(null);
	let actionLoading = $state<string | null>(null);

	// Opprett-skjema
	let showCreateForm = $state(false);
	let newProvider = $state('openrouter');
	let newLabel = $state('');
	let newApiKey = $state('');
	let testResult = $state<TestKeyResponse | null>(null);
	let testLoading = $state(false);

	const providers = [
		{ value: 'openrouter', label: 'OpenRouter' },
		{ value: 'anthropic', label: 'Anthropic' },
		{ value: 'openai', label: 'OpenAI' },
		{ value: 'gemini', label: 'Google Gemini' },
		{ value: 'xai', label: 'xAI' },
		{ value: 'elevenlabs', label: 'ElevenLabs' },
		{ value: 'other', label: 'Annen' }
	];

	function providerLabel(provider: string): string {
		return providers.find((p) => p.value === provider)?.label ?? provider;
	}

	$effect(() => {
		if (!accessToken) return;
		loadKeys();
		const interval = setInterval(loadKeys, 15000);
		return () => clearInterval(interval);
	});

	async function loadKeys() {
		if (!accessToken) return;
		try {
			const res = await fetchApiKeys(accessToken);
			keys = res.keys;
			error = null;
		} catch (e) {
			error = String(e);
		}
	}

	function toggleCreateForm() {
		showCreateForm = !showCreateForm;
		testResult = null;
		newApiKey = '';
		newLabel = '';
		newProvider = 'openrouter';
	}

	async function handleTest() {
		if (!accessToken || !newApiKey.trim()) return;
		testLoading = true;
		testResult = null;
		try {
			testResult = await testApiKey(accessToken, {
				provider: newProvider,
				api_key: newApiKey.trim()
			});
		} catch (e) {
			testResult = { success: false, message: String(e) };
		} finally {
			testLoading = false;
		}
	}

	async function handleCreate() {
		if (!accessToken || !newApiKey.trim()) return;
		actionLoading = 'create';
		error = null;
		try {
			await createApiKey(accessToken, {
				provider: newProvider,
				label: newLabel.trim() || undefined,
				api_key: newApiKey.trim()
			});
			newApiKey = '';
			newLabel = '';
			testResult = null;
			showCreateForm = false;
			await loadKeys();
		} catch (e) {
			error = String(e);
		} finally {
			actionLoading = null;
		}
	}

	async function handleToggleActive(id: string) {
		if (!accessToken) return;
		actionLoading = `toggle-${id}`;
		error = null;
		try {
			await deactivateApiKey(accessToken, id);
			await loadKeys();
		} catch (e) {
			error = String(e);
		} finally {
			actionLoading = null;
		}
	}

	async function handleDelete(id: string) {
		if (!accessToken) return;
		if (!confirm('Slett nøkkelen permanent? Dette kan ikke angres.')) return;
		actionLoading = `del-${id}`;
		error = null;
		try {
			await deleteApiKey(accessToken, id);
			await loadKeys();
		} catch (e) {
			error = String(e);
		} finally {
			actionLoading = null;
		}
	}

	function timeAgo(iso: string | null): string {
		if (!iso) return 'Aldri';
		const diff = Date.now() - new Date(iso).getTime();
		const mins = Math.floor(diff / 60000);
		if (mins < 1) return 'nå';
		if (mins < 60) return `${mins}m`;
		const hours = Math.floor(mins / 60);
		if (hours < 24) return `${hours}t`;
		const days = Math.floor(hours / 24);
		return `${days}d`;
	}
</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-3xl items-center justify-between px-4 py-3">
			<div class="flex items-center gap-3">
				<a href="/" class="text-sm text-gray-500 hover:text-gray-700">Hjem</a>
				<a href="/admin" class="text-sm text-gray-500 hover:text-gray-700">Admin</a>
				<h1 class="text-lg font-semibold text-gray-900">API-nokler</h1>
			</div>
			<nav class="flex gap-2 text-sm">
				<a href="/admin" class="rounded-lg bg-gray-100 px-3 py-1.5 text-gray-700 hover:bg-gray-200">
					Vedlikehold
				</a>
				<a href="/admin/ai" class="rounded-lg bg-gray-100 px-3 py-1.5 text-gray-700 hover:bg-gray-200">
					AI
				</a>
				<a href="/admin/webhooks" class="rounded-lg bg-gray-100 px-3 py-1.5 text-gray-700 hover:bg-gray-200">
					Webhooks
				</a>
			</nav>
		</div>
	</header>

	<main class="mx-auto max-w-3xl px-4 py-6">
		{#if !accessToken}
			<p class="text-sm text-gray-400">Logg inn for tilgang.</p>
		{:else}
			{#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}

			<div class="mb-4 flex items-center justify-between">
				<h2 class="text-base font-semibold text-gray-800">
					API-nokler
					<span class="ml-1 text-sm font-normal text-gray-400">({keys.length})</span>
				</h2>
				<button
					onclick={toggleCreateForm}
					class="rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-700"
				>
					{showCreateForm ? 'Avbryt' : 'Legg til nokkel'}
				</button>
			</div>

			{#if showCreateForm}
				<section class="mb-4 rounded-lg border border-blue-200 bg-blue-50 p-4">
					<h3 class="mb-3 text-sm font-semibold text-gray-800">Ny API-nokkel</h3>
					<div class="space-y-3">
						<div>
							<label for="ak-provider" class="mb-1 block text-xs font-medium text-gray-600">
								Provider
							</label>
							<select
								id="ak-provider"
								bind:value={newProvider}
								class="w-full rounded border border-gray-300 px-2 py-1.5 text-sm"
							>
								{#each providers as p (p.value)}
									<option value={p.value}>{p.label}</option>
								{/each}
							</select>
						</div>
						<div>
							<label for="ak-label" class="mb-1 block text-xs font-medium text-gray-600">
								Label (valgfritt)
							</label>
							<input
								id="ak-label"
								type="text"
								placeholder="F.eks. Prod, Vegards konto"
								bind:value={newLabel}
								class="w-full rounded border border-gray-300 px-2 py-1.5 text-sm"
							/>
						</div>
						<div>
							<label for="ak-key" class="mb-1 block text-xs font-medium text-gray-600">
								API-nokkel
							</label>
							<input
								id="ak-key"
								type="password"
								placeholder="sk-..."
								bind:value={newApiKey}
								class="w-full rounded border border-gray-300 px-2 py-1.5 text-sm font-mono"
							/>
						</div>

						{#if testResult}
							<div
								class="rounded-lg border p-2 text-sm {testResult.success
									? 'border-green-200 bg-green-50 text-green-700'
									: 'border-red-200 bg-red-50 text-red-700'}"
							>
								{testResult.message}
							</div>
						{/if}

						<div class="flex gap-2">
							<button
								onclick={handleTest}
								disabled={!newApiKey.trim() || testLoading}
								class="rounded-lg bg-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-300 disabled:opacity-50"
							>
								{testLoading ? 'Tester...' : 'Test tilkobling'}
							</button>
							<button
								onclick={handleCreate}
								disabled={!newApiKey.trim() || actionLoading === 'create'}
								class="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
							>
								{actionLoading === 'create' ? 'Lagrer...' : 'Lagre'}
							</button>
						</div>
					</div>
				</section>
			{/if}

			{#if keys.length === 0 && !loading}
				<div class="rounded-lg border border-gray-200 bg-white p-8 text-center text-sm text-gray-400">
					Ingen API-nokler registrert enna.
				</div>
			{:else}
				<div class="space-y-3">
					{#each keys as key (key.id)}
						<div class="rounded-lg border border-gray-200 bg-white shadow-sm">
							<div class="flex items-start justify-between p-4">
								<div class="min-w-0 flex-1">
									<div class="flex items-center gap-2">
										<h3 class="text-sm font-semibold text-gray-800">
											{providerLabel(key.provider)}
										</h3>
										{#if key.label}
											<span class="rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-500">
												{key.label}
											</span>
										{/if}
										<span
											class="rounded-full px-2 py-0.5 text-xs {key.is_active
												? 'bg-green-100 text-green-700'
												: 'bg-gray-100 text-gray-500'}"
										>
											{key.is_active ? 'Aktiv' : 'Inaktiv'}
										</span>
									</div>

									<div class="mt-1.5 flex items-center gap-4 text-xs text-gray-400">
										<span class="font-mono">{key.key_hint || '****'}</span>
										<span>Brukt {key.usage_count}x</span>
										<span>Sist brukt: {timeAgo(key.last_used)}</span>
										<span>Lagt til {new Date(key.created_at).toLocaleDateString('nb-NO')}</span>
									</div>
								</div>

								<div class="ml-3 flex shrink-0 gap-2">
									<button
										onclick={() => handleToggleActive(key.id)}
										disabled={actionLoading === `toggle-${key.id}`}
										class="rounded px-2 py-1 text-xs {key.is_active
											? 'bg-amber-100 text-amber-700 hover:bg-amber-200'
											: 'bg-green-100 text-green-700 hover:bg-green-200'} disabled:opacity-50"
									>
										{#if actionLoading === `toggle-${key.id}`}
											...
										{:else}
											{key.is_active ? 'Deaktiver' : 'Aktiver'}
										{/if}
									</button>
									<button
										onclick={() => handleDelete(key.id)}
										disabled={actionLoading === `del-${key.id}`}
										class="rounded bg-red-100 px-2 py-1 text-xs text-red-700 hover:bg-red-200 disabled:opacity-50"
									>
										{actionLoading === `del-${key.id}` ? '...' : 'Slett'}
									</button>
								</div>
							</div>
						</div>
					{/each}
				</div>
			{/if}
		{/if}
	</main>
</div>
