<script lang="ts">
	import { Card, Button, FormField } from '$lib/components';
	import { updateSettings, getPiModels } from '$lib/api/admin';
	import { toast } from '$lib/stores/toast.svelte';
	import { data } from '$lib/stores/data.svelte';

	const CLAUDE_MODELS = ['claude-sonnet-4-6', 'claude-opus-4-6', 'claude-haiku-4-5-20251001', 'claude-sonnet-4-5-20250929', 'claude-opus-4-5-20251101', 'claude-opus-4-1-20250805', 'claude-opus-4-20250514', 'claude-sonnet-4-20250514', 'claude-3-7-sonnet-20250219', 'claude-3-5-sonnet-20241022', 'claude-3-5-haiku-20241022', 'claude-3-opus-20240229'];
	const CODEX_MODELS = ['gpt-5.4', 'gpt-5.2', 'gpt-4o', 'o1-preview', 'o1-mini'];

	let savingSettings = $state(false);
	let defaultProvider = $state('claude');
	let defaultModel = $state('claude-sonnet-4-6');
	let defaultPiBackend = $state('anthropic');
	let conciergeBotUserId = $state('');
	let conciergeTenantId = $state('');

	// Pi model registry
	let piProviders = $state<{ id: string; label: string; modelCount: number }[]>([]);
	let piModelsByProvider = $state<Record<string, { id: string; name: string }[]>>({});
	let loadingPiModels = $state(false);

	let settingsInitialized = $state(false);

	$effect(() => {
		if (data.settings && !settingsInitialized) {
			defaultProvider = data.settings.default_provider;
			defaultModel = data.settings.default_model;
			defaultPiBackend = data.settings.default_pi_backend ?? 'anthropic';
			conciergeBotUserId = data.settings.concierge_bot_user_id ?? '';
			conciergeTenantId = data.settings.concierge_tenant_id ?? '';
			settingsInitialized = true;
		}
	});

	$effect(() => {
		if (defaultProvider === 'pi' && piProviders.length === 0 && !loadingPiModels) {
			loadingPiModels = true;
			getPiModels().then(result => {
				piProviders = result.providers;
				piModelsByProvider = result.models;
				loadingPiModels = false;
			}).catch(() => { loadingPiModels = false; });
		}
	});

	$effect(() => {
		if (defaultProvider === 'claude' && !CLAUDE_MODELS.includes(defaultModel)) {
			defaultModel = CLAUDE_MODELS[0];
		} else if (defaultProvider === 'codex' && !CODEX_MODELS.includes(defaultModel)) {
			defaultModel = CODEX_MODELS[0];
		} else if (defaultProvider === 'pi') {
			const backendModels = piModelsByProvider[defaultPiBackend] ?? [];
			if (backendModels.length > 0 && !backendModels.find(m => m.id === defaultModel)) {
				defaultModel = backendModels[0].id;
			}
		}
	});

	async function handleSave() {
		savingSettings = true;
		try {
			await updateSettings({
				default_provider: defaultProvider,
				default_model: defaultModel,
				default_pi_backend: defaultPiBackend,
				concierge_bot_user_id: conciergeBotUserId,
				concierge_tenant_id: conciergeTenantId,
			});
			toast.success('Settings saved');
			await data.refetchSettings();
		} catch (e: any) {
			toast.error(e.message || 'Failed to save settings');
		} finally {
			savingSettings = false;
		}
	}
</script>

<Card title="Global Defaults" compact>
	{#snippet actions()}
		<Button variant="primary" size="sm" loading={savingSettings} onclick={handleSave}>
			Save
		</Button>
	{/snippet}
	<div class="settings-grid">
		<FormField label="Default Provider">
			<select bind:value={defaultProvider}>
				<option value="claude">Claude</option>
				<option value="codex">Codex</option>
				<option value="pi">Pi</option>
			</select>
		</FormField>
		{#if defaultProvider === 'pi'}
		<FormField label="Pi Backend" hint="LLM provider used by the pi runtime">
			{#if loadingPiModels}
				<span class="hint">Loading providers...</span>
			{:else}
			<select bind:value={defaultPiBackend}>
				{#each piProviders as p}
					<option value={p.id}>{p.label} ({p.modelCount} models)</option>
				{/each}
			</select>
			{/if}
		</FormField>
		{/if}
		<FormField label="Default Model">
			<select bind:value={defaultModel}>
				{#if defaultProvider === 'claude'}
					{#each CLAUDE_MODELS as m}
						<option value={m}>{m}</option>
					{/each}
				{:else if defaultProvider === 'codex'}
					{#each CODEX_MODELS as m}
						<option value={m}>{m}</option>
					{/each}
				{:else if defaultProvider === 'pi'}
					{#each (piModelsByProvider[defaultPiBackend] ?? []) as m}
						<option value={m.id}>{m.name}</option>
					{/each}
				{/if}
			</select>
		</FormField>
		<FormField label="Concierge Tenant ID" hint="Tenant that handles welcome DMs and pairing (e.g. gaia)">
			<input type="text" bind:value={conciergeTenantId} placeholder="e.g. gaia" />
		</FormField>
		<FormField label="Concierge Bot User ID" hint="Discord user ID of the concierge bot (for channel permissions)">
			<input type="text" bind:value={conciergeBotUserId} placeholder="Discord user ID" class="mono" />
		</FormField>
	</div>
</Card>

<style>
	.settings-grid {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
		gap: 20px;
		padding: 4px 0;
	}

	@media (max-width: 768px) {
		.settings-grid {
			grid-template-columns: 1fr;
		}
	}
</style>
