<script lang="ts">
	import { onDestroy } from 'svelte';
	import StatBadge from '$lib/components/StatBadge.svelte';
	import type {
		EmbeddingProfileDto,
		EmbeddingSettingsDto,
		EmbeddingSettingsUpdateDto
	} from '$lib/dtos/embedding-settings';
	import type { PageProps } from './$types';

	// ---------------------------------------------------------------------------
	// Provider presets
	// ---------------------------------------------------------------------------

	const PROVIDER_PRESETS = [
		{
			name: 'OpenAI',
			baseUrl: 'https://api.openai.com/v1',
			model: 'text-embedding-3-small',
			dimensions: 1536
		},
		{
			name: 'Ollama (local)',
			baseUrl: 'http://localhost:11434/v1',
			model: 'nomic-embed-text',
			dimensions: 768
		},
		{
			name: 'Azure OpenAI',
			baseUrl: 'https://{resource}.openai.azure.com/openai/deployments/{deployment}/v1',
			model: 'text-embedding-3-small',
			dimensions: 1536
		}
	];

	// ---------------------------------------------------------------------------
	// State
	// ---------------------------------------------------------------------------

	let { data }: PageProps = $props();

	function getInitialSettings(): EmbeddingSettingsDto {
		return data.settings;
	}

	function getInitialLocalProviderAvailability(): boolean {
		return data.localProviderAvailable;
	}

	let settingsOverride = $state<EmbeddingSettingsDto | null>(null);
	let provider = $state<'none' | 'openai' | 'local'>(
		resolveProvider(getInitialSettings().activeProfile)
	);
	let baseUrl = $state(resolveBaseUrl(getInitialSettings()));
	let apiKey = $state('');
	let model = $state(resolveModel(getInitialSettings()));
	let dimensions = $state<number | undefined>(resolveDimensions(getInitialSettings()));
	let openaiProfileId = $state(resolveOpenAiProfileId(getInitialSettings()));

	let testStatus = $state<'idle' | 'testing' | 'ok' | 'error'>('idle');
	let testError = $state<string | null>(null);
	let testDimensions = $state<number | null>(null);

	let saving = $state(false);
	let saveStatus = $state<'idle' | 'ok' | 'error'>('idle');
	let saveError = $state<string | null>(null);
	let saveStatusTimer: ReturnType<typeof setTimeout> | null = null;

	let concurrencyInput = $derived(data.indexingConcurrency);
	let concurrencySaving = $state(false);
	let concurrencySaveStatus = $state<'idle' | 'ok' | 'error'>('idle');
	let concurrencySaveError = $state<string | null>(null);
	let concurrencySaveStatusTimer: ReturnType<typeof setTimeout> | null = null;

	const currentSettings = $derived(settingsOverride ?? data.settings);
	const activeProfile = $derived(currentSettings.activeProfile);
	const activeConfigEntries = $derived(activeProfile?.configEntries ?? []);

	onDestroy(() => {
		if (saveStatusTimer) clearTimeout(saveStatusTimer);
		if (concurrencySaveStatusTimer) clearTimeout(concurrencySaveStatusTimer);
	});

	// ---------------------------------------------------------------------------
	// Actions
	// ---------------------------------------------------------------------------

	function applyPreset(preset: (typeof PROVIDER_PRESETS)[number]) {
		baseUrl = preset.baseUrl;
		model = preset.model;
		dimensions = preset.dimensions;
		testStatus = 'idle';
		testError = null;
		testDimensions = null;
	}

	async function testConnection() {
		if (provider !== 'openai') {
			return;
		}

		testStatus = 'testing';
		testError = null;
		testDimensions = null;
		try {
			const res = await fetch('/api/v1/settings/embedding/test', {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({
					id: openaiProfileId,
					title: 'OpenAI-compatible',
					providerKind: 'openai-compatible',
					model,
					dimensions: dimensions ?? 1536,
					config: { baseUrl, apiKey, model, ...(dimensions ? { dimensions } : {}) }
				})
			});
			if (res.ok) {
				const data = await res.json();
				testStatus = 'ok';
				testDimensions = data.dimensions ?? null;
			} else {
				const data = await res.json();
				testStatus = 'error';
				testError = data.error ?? 'Unknown error';
			}
		} catch (e) {
			testStatus = 'error';
			testError = (e as Error).message;
		}
	}

	async function save() {
		saving = true;
		saveStatus = 'idle';
		saveError = null;
		try {
			const res = await fetch('/api/v1/settings/embedding', {
				method: 'PUT',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify(buildSaveRequest())
			});
			if (res.ok) {
				settingsOverride = (await res.json()) as EmbeddingSettingsDto;
				saveStatus = 'ok';
				if (saveStatusTimer) clearTimeout(saveStatusTimer);
				saveStatusTimer = setTimeout(() => {
					saveStatus = 'idle';
					saveStatusTimer = null;
				}, 3000);
			} else {
				const data = await res.json();
				saveStatus = 'error';
				saveError = data.error ?? 'Save failed';
			}
		} catch (e) {
			saveStatus = 'error';
			saveError = (e as Error).message;
		} finally {
			saving = false;
		}
	}

	function handleSubmit(event: SubmitEvent) {
		event.preventDefault();
		void save();
	}

	async function saveConcurrency() {
		concurrencySaving = true;
		concurrencySaveStatus = 'idle';
		concurrencySaveError = null;
		try {
			const res = await fetch('/api/v1/settings/indexing', {
				method: 'PUT',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ concurrency: concurrencyInput })
			});
			if (res.ok) {
				const updated = await res.json();
				concurrencyInput = updated.concurrency;
				concurrencySaveStatus = 'ok';
				if (concurrencySaveStatusTimer) clearTimeout(concurrencySaveStatusTimer);
				concurrencySaveStatusTimer = setTimeout(() => {
					concurrencySaveStatus = 'idle';
					concurrencySaveStatusTimer = null;
				}, 3000);
			} else {
				const data = await res.json();
				concurrencySaveStatus = 'error';
				concurrencySaveError = data.error ?? 'Save failed';
			}
		} catch (e) {
			concurrencySaveStatus = 'error';
			concurrencySaveError = (e as Error).message;
		} finally {
			concurrencySaving = false;
		}
	}

	function getOpenAiProfile(settings: EmbeddingSettingsDto): EmbeddingProfileDto | null {
		return settings.profiles.find((profile) => profile.providerKind === 'openai-compatible') ?? null;
	}

	function resolveProvider(profile: EmbeddingProfileDto | null): 'none' | 'openai' | 'local' {
		if (!profile) return 'none';
		if (profile.providerKind === 'local-transformers') return 'local';
		if (profile.providerKind === 'openai-compatible') return 'openai';
		return 'none';
	}

	function resolveBaseUrl(settings: EmbeddingSettingsDto): string {
		const profile = settings.activeProfile?.providerKind === 'openai-compatible'
			? settings.activeProfile
			: getOpenAiProfile(settings);
		return typeof profile?.config.baseUrl === 'string'
			? profile.config.baseUrl
			: 'https://api.openai.com/v1';
	}

	function resolveModel(settings: EmbeddingSettingsDto): string {
		const profile = settings.activeProfile?.providerKind === 'openai-compatible'
			? settings.activeProfile
			: getOpenAiProfile(settings);
		return typeof profile?.config.model === 'string'
			? profile.config.model
			: profile?.model ?? 'text-embedding-3-small';
	}

	function resolveDimensions(settings: EmbeddingSettingsDto): number | undefined {
		const profile = settings.activeProfile?.providerKind === 'openai-compatible'
			? settings.activeProfile
			: getOpenAiProfile(settings);
		return profile?.dimensions ?? 1536;
	}

	function resolveOpenAiProfileId(settings: EmbeddingSettingsDto): string {
		const profile = getOpenAiProfile(settings);
		return profile?.id ?? 'openai-default';
	}

	function buildSaveRequest(): EmbeddingSettingsUpdateDto {
		if (provider === 'none') {
			return { activeProfileId: null };
		}

		if (provider === 'local') {
			return { activeProfileId: 'local-default' };
		}

		return {
			activeProfileId: openaiProfileId,
			profile: {
				id: openaiProfileId,
				providerKind: 'openai-compatible',
				title: 'OpenAI-compatible',
				model,
				dimensions: dimensions ?? 1536,
				config: { baseUrl, apiKey, model, ...(dimensions ? { dimensions } : {}) }
			}
		};
	}

	function formatTimestamp(timestamp: number): string {
		const normalizedTimestamp = timestamp > 1_000_000_000_000 ? timestamp : timestamp * 1000;
		return new Date(normalizedTimestamp).toLocaleString();
	}
</script>

<svelte:head>
	<title>Settings — TrueRef</title>
</svelte:head>

<div class="mb-6">
	<h1 class="text-xl font-semibold text-gray-900">Settings</h1>
	<p class="mt-0.5 text-sm text-gray-500">Configure TrueRef embedding and indexing options</p>
</div>

<div class="mb-4 grid gap-4 lg:grid-cols-[1.2fr_0.8fr]">
	<div class="rounded-xl border border-gray-200 bg-white p-6">
		<h2 class="mb-1 text-base font-semibold text-gray-900">Current Active Profile</h2>
		<p class="mb-4 text-sm text-gray-500">
			This is the profile used for semantic indexing and retrieval right now.
		</p>

		{#if activeProfile}
			<div class="grid gap-4 md:grid-cols-2">
				<div class="space-y-4">
					<div>
						<p class="text-lg font-semibold text-gray-900">{activeProfile.title}</p>
						<p class="mt-1 text-sm text-gray-500">Profile ID: {activeProfile.id}</p>
					</div>

					<dl class="rounded-lg border border-gray-200 bg-gray-50 p-4 text-sm">
						<div class="grid grid-cols-[110px_1fr] gap-x-4 gap-y-1 border-b border-gray-200 pb-3">
							<dt class="font-medium text-gray-500">Provider</dt>
							<dd class="font-semibold text-gray-900">{activeProfile.providerKind}</dd>
							<dt class="font-medium text-gray-500">Model</dt>
							<dd class="break-all font-semibold text-gray-900">{activeProfile.model}</dd>
							<dt class="font-medium text-gray-500">Dimensions</dt>
							<dd class="font-semibold text-gray-900">{activeProfile.dimensions}</dd>
						</div>

						<div class="grid grid-cols-[110px_1fr] gap-x-4 gap-y-2 pt-3">
						<dt class="text-gray-500">Enabled</dt>
						<dd class="font-medium text-gray-800">{activeProfile.enabled ? 'Yes' : 'No'}</dd>
						<dt class="text-gray-500">Default</dt>
						<dd class="font-medium text-gray-800">{activeProfile.isDefault ? 'Yes' : 'No'}</dd>
						<dt class="text-gray-500">Updated</dt>
						<dd class="font-medium text-gray-800">{formatTimestamp(activeProfile.updatedAt)}</dd>
						</div>
					</dl>
				</div>

				<div class="rounded-lg border border-gray-200 bg-gray-50 p-4">
					<p class="text-sm font-medium text-gray-800">Provider configuration</p>
					<p class="mb-3 mt-1 text-sm text-gray-500">
						These are the provider-specific settings currently saved for the active profile.
					</p>

					{#if activeConfigEntries.length > 0}
						<ul class="space-y-2 text-sm">
							{#each activeConfigEntries as entry (entry.key)}
								<li class="flex items-start justify-between gap-4 border-b border-gray-200 pb-2 last:border-b-0 last:pb-0">
									<span class="font-medium text-gray-600">{entry.key}</span>
									<span class={entry.redacted ? 'text-gray-500' : 'text-gray-800'}>{entry.value}</span>
								</li>
							{/each}
						</ul>
					{:else}
						<p class="text-sm text-gray-500">
							No provider-specific configuration is stored for this profile.
						</p>
						<p class="mt-2 text-sm text-gray-500">
							For <span class="font-medium text-gray-700">OpenAI-compatible</span> profiles, edit the
							settings in the <span class="font-medium text-gray-700">Embedding Provider</span> form
							below. The built-in <span class="font-medium text-gray-700">Local Model</span> profile
							does not currently expose extra configurable fields.
						</p>
					{/if}
				</div>
			</div>
		{:else}
			<div class="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
				Embeddings are currently disabled. Keyword search remains available, but no embedding profile is active.
			</div>
		{/if}
	</div>

	<div class="rounded-xl border border-gray-200 bg-white p-6">
		<h2 class="mb-1 text-base font-semibold text-gray-900">Profile Inventory</h2>
		<p class="mb-4 text-sm text-gray-500">Profiles stored in the database and available for activation.</p>
		<div class="grid grid-cols-2 gap-3">
			<StatBadge label="Profiles" value={String(currentSettings.profiles.length)} />
			<StatBadge label="Active" value={activeProfile ? '1' : '0'} />
		</div>
		<div class="mt-4 space-y-2">
			{#each currentSettings.profiles as profile (profile.id)}
				<div class="rounded-lg border border-gray-200 px-3 py-2 text-sm">
					<div class="flex items-center justify-between gap-3">
						<div>
							<p class="font-medium text-gray-900">{profile.title}</p>
							<p class="text-gray-500">{profile.id}</p>
						</div>
						{#if profile.id === currentSettings.activeProfileId}
							<span class="rounded-full bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700">Active</span>
						{/if}
					</div>
				</div>
			{/each}
		</div>
	</div>
</div>

<div class="rounded-xl border border-gray-200 bg-white p-6">
	<h2 class="mb-1 text-base font-semibold text-gray-900">Embedding Provider</h2>
	<p class="mb-4 text-sm text-gray-500">
		Embeddings enable semantic search. Without them, only keyword search (FTS5) is used.
	</p>

	<form class="space-y-4" onsubmit={handleSubmit}>
			<!-- Provider selector -->
			<div class="mb-4 flex gap-2">
				{#each ['none', 'openai', 'local'] as p (p)}
					<button
						type="button"
						onclick={() => {
							provider = p as 'none' | 'openai' | 'local';
							testStatus = 'idle';
							testError = null;
						}}
						class={[
							'rounded-lg px-4 py-2 text-sm',
							provider === p
								? 'bg-blue-600 text-white'
								: 'border border-gray-200 text-gray-700 hover:bg-gray-50'
						].join(' ')}
					>
						{p === 'none'
							? 'None (FTS5 only)'
							: p === 'openai'
								? 'OpenAI-compatible'
								: 'Local Model'}
					</button>
				{/each}
			</div>

			<!-- None warning -->
			{#if provider === 'none'}
				<div class="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-700">
					Search will use keyword matching only. Results may be less relevant for complex questions.
				</div>
			{/if}

			<!-- OpenAI-compatible form -->
			{#if provider === 'openai'}
				<div class="space-y-3">
					<!-- Preset buttons -->
					<div class="flex flex-wrap gap-2">
						{#each PROVIDER_PRESETS as preset (preset.name)}
							<button
								type="button"
								onclick={() => applyPreset(preset)}
								class="rounded border border-gray-200 px-2.5 py-1 text-xs text-gray-600 hover:bg-gray-50"
							>
								{preset.name}
							</button>
						{/each}
					</div>

					<label class="block" for="embedding-base-url">
						<span class="text-sm font-medium text-gray-700">Base URL</span>
						<input
							id="embedding-base-url"
							name="baseUrl"
							type="text"
							autocomplete="url"
							bind:value={baseUrl}
							class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
						/>
					</label>

					<label class="block" for="embedding-api-key">
						<span class="text-sm font-medium text-gray-700">API Key</span>
						<input
							id="embedding-api-key"
							name="apiKey"
							type="password"
							autocomplete="off"
							bind:value={apiKey}
							placeholder="sk-…"
							class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
						/>
					</label>

					<label class="block" for="embedding-model">
						<span class="text-sm font-medium text-gray-700">Model</span>
						<input
							id="embedding-model"
							name="model"
							type="text"
							autocomplete="off"
							bind:value={model}
							class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
						/>
					</label>

					<label class="block" for="embedding-dimensions">
						<span class="text-sm font-medium text-gray-700">Dimensions (optional override)</span>
						<input
							id="embedding-dimensions"
							name="dimensions"
							type="number"
							inputmode="numeric"
							bind:value={dimensions}
							class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
						/>
					</label>

					<!-- Test connection row -->
					<div class="flex items-center gap-3">
						<button
							type="button"
							onclick={testConnection}
							disabled={testStatus === 'testing'}
							class="rounded-lg border border-gray-300 px-3 py-1.5 text-sm hover:bg-gray-50 disabled:opacity-50"
						>
							{testStatus === 'testing' ? 'Testing…' : 'Test Connection'}
						</button>

						{#if testStatus === 'ok'}
							<span class="text-sm text-green-600">
								Connection successful
								{#if testDimensions}— {testDimensions} dimensions{/if}
							</span>
						{:else if testStatus === 'error'}
							<span class="text-sm text-red-600">
								{testError}
							</span>
						{/if}
					</div>
				</div>
			{/if}

			<!-- Local model section -->
			{#if provider === 'local'}
				<div class="rounded-lg border border-gray-200 bg-gray-50 p-4 text-sm">
					<p class="font-medium text-gray-800">Local ONNX model via @xenova/transformers</p>
					<p class="mt-1 text-gray-500">Model: Xenova/all-MiniLM-L6-v2 · 384 dimensions</p>
					{#if getInitialLocalProviderAvailability()}
						<p class="mt-2 text-green-600">@xenova/transformers is installed and ready.</p>
					{:else}
						<p class="mt-2 text-amber-700">
							@xenova/transformers is not installed. Run
							<code class="rounded bg-amber-100 px-1 py-0.5 font-mono text-xs"
								>npm install @xenova/transformers</code
							>
							to enable local embeddings.
						</p>
					{/if}
				</div>
			{/if}

			<!-- Indexing section -->
			<div class="space-y-3 rounded-lg border border-gray-200 bg-white p-4">
				<div>
					<label for="concurrency" class="block text-sm font-medium text-gray-700">
						Concurrent Workers
					</label>
					<p class="mt-0.5 text-xs text-gray-500">
						Number of parallel indexing workers. Range: 1 to 8.
					</p>
				</div>

				<div class="flex items-center gap-3">
					<input
						id="concurrency"
						type="number"
						min="1"
						max="8"
						inputmode="numeric"
						bind:value={concurrencyInput}
						disabled={concurrencySaving}
						class="w-20 rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none disabled:opacity-50"
					/>
					<button
						type="button"
						onclick={saveConcurrency}
						disabled={concurrencySaving}
						class="rounded-lg bg-blue-600 px-3 py-2 text-sm text-white hover:bg-blue-700 disabled:opacity-50"
					>
						{concurrencySaving ? 'Saving…' : 'Save'}
					</button>

					{#if concurrencySaveStatus === 'ok'}
						<span class="text-sm text-green-600">✓ Saved</span>
					{:else if concurrencySaveStatus === 'error'}
						<span class="text-sm text-red-600">{concurrencySaveError}</span>
					{/if}
				</div>
			</div>

			<!-- Save feedback banners -->
			{#if saveStatus === 'ok'}
				<div
					class="mt-4 flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-sm font-medium text-green-700"
				>
					<svg
						xmlns="http://www.w3.org/2000/svg"
						class="h-4 w-4 shrink-0"
						viewBox="0 0 20 20"
						fill="currentColor"
						aria-hidden="true"
					>
						<path
							fill-rule="evenodd"
							d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
							clip-rule="evenodd"
						/>
					</svg>
					Settings saved successfully.
				</div>
			{:else if saveStatus === 'error'}
				<div
					class="mt-4 flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm font-medium text-red-700"
				>
					<svg
						xmlns="http://www.w3.org/2000/svg"
						class="h-4 w-4 shrink-0"
						viewBox="0 0 20 20"
						fill="currentColor"
						aria-hidden="true"
					>
						<path
							fill-rule="evenodd"
							d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
							clip-rule="evenodd"
						/>
					</svg>
					{saveError}
				</div>
			{/if}

			<!-- Save row -->
			<div class="mt-4 flex items-center justify-end">
				<button
					type="submit"
					disabled={saving}
					class="rounded-lg bg-blue-600 px-4 py-2 text-sm text-white hover:bg-blue-700 disabled:opacity-50"
				>
					{saving ? 'Saving…' : 'Save Settings'}
				</button>
			</div>
	</form>
</div>

<!-- About card -->
<div class="mt-4 rounded-xl border border-gray-200 bg-white p-6">
	<h2 class="mb-1 text-base font-semibold text-gray-900">About TrueRef</h2>
	<p class="mb-4 text-sm text-gray-500">
		Self-hosted documentation intelligence platform — a full-stack clone of context7.
	</p>
	<div class="grid grid-cols-2 gap-3 sm:grid-cols-3">
		<StatBadge label="API Version" value="v1" />
		<StatBadge label="DB" value="SQLite" />
		<StatBadge label="Search" value="FTS5 + Vec" />
	</div>
</div>
