<script lang="ts">
	import StatBadge from '$lib/components/StatBadge.svelte';

	// ---------------------------------------------------------------------------
	// 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 provider = $state<'none' | 'openai' | 'local'>('none');
	let baseUrl = $state('https://api.openai.com/v1');
	let apiKey = $state('');
	let model = $state('text-embedding-3-small');
	let dimensions = $state<number | undefined>(1536);

	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 localAvailable = $state<boolean | null>(null);
	let loading = $state(true);

	// ---------------------------------------------------------------------------
	// Load current config + probe local provider on mount
	// ---------------------------------------------------------------------------

	$effect(() => {
		let cancelled = false;

		(async () => {
			try {
				const res = await fetch('/api/v1/settings/embedding');
				if (!cancelled && res.ok) {
					const data = await res.json();
					provider = data.provider ?? 'none';
					if (data.openai) {
						baseUrl = data.openai.baseUrl ?? baseUrl;
						model = data.openai.model ?? model;
						dimensions = data.openai.dimensions ?? dimensions;
						// apiKey is intentionally not returned by the server; leave blank
					}
				}
			} catch {
				// Non-fatal — fall back to defaults
			} finally {
				if (!cancelled) loading = false;
			}

			// Probe whether the local provider is available
			try {
				const res = await fetch('/api/v1/settings/embedding/test');
				if (!cancelled && res.ok) {
					const data = await res.json();
					localAvailable = data.available ?? false;
				}
			} catch {
				if (!cancelled) localAvailable = false;
			}
		})();

		return () => {
			cancelled = true;
			if (saveStatusTimer) clearTimeout(saveStatusTimer);
		};
	});

	// ---------------------------------------------------------------------------
	// 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() {
		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({ provider, openai: { baseUrl, apiKey, model, 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({ provider, openai: { baseUrl, apiKey, model, dimensions } })
			});
			if (res.ok) {
				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();
	}
</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>

<!-- Embedding Provider Card -->
<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>

	{#if loading}
		<p class="text-sm text-gray-400">Loading current configuration…</p>
	{:else}
		<form class="space-y-4" onsubmit={handleSubmit}>
			<!-- Provider selector -->
			<div class="mb-4 flex gap-2">
				{#each ['none', 'openai', 'local'] as 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}
							<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 localAvailable === null}
						<p class="mt-2 text-gray-400">Checking availability…</p>
					{:else if localAvailable}
						<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}

			<!-- 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>
	{/if}
</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>
