<script lang="ts">
	import { updateNode } from '$lib/api';
	import { traitCatalog } from '$lib/traits';
	import PodcastTraitAdmin from './PodcastTraitAdmin.svelte';

	interface Props {
		collectionId: string;
		accessToken: string;
		/** Current traits object from collection metadata */
		traits: Record<string, Record<string, unknown>>;
		/** Current full metadata (so we preserve non-trait fields) */
		metadata: Record<string, unknown>;
		onclose: () => void;
	}

	let { collectionId, accessToken, traits, metadata, onclose }: Props = $props();

	// Local working copy of traits — start from current state
	let workingTraits: Record<string, Record<string, unknown>> = $state({});
	let isSaving = $state(false);
	let error: string | null = $state(null);
	let successMsg: string | null = $state(null);

	// Editing state for per-trait config
	let editingTrait: string | null = $state(null);
	let configKey = $state('');
	let configValue = $state('');

	// Initialize working copy from props
	$effect(() => {
		workingTraits = structuredClone(traits);
	});

	const activeTraitNames = $derived(Object.keys(workingTraits).sort());

	const hasChanges = $derived(() => {
		const currentKeys = Object.keys(traits).sort();
		const workingKeys = Object.keys(workingTraits).sort();
		if (currentKeys.length !== workingKeys.length) return true;
		if (currentKeys.join(',') !== workingKeys.join(',')) return true;
		// Check config changes
		for (const key of currentKeys) {
			if (JSON.stringify(traits[key]) !== JSON.stringify(workingTraits[key])) return true;
		}
		return false;
	});

	function addTrait(trait: string) {
		if (!(trait in workingTraits)) {
			workingTraits = { ...workingTraits, [trait]: {} };
		}
	}

	function removeTrait(trait: string) {
		const next = { ...workingTraits };
		delete next[trait];
		workingTraits = next;
		if (editingTrait === trait) editingTrait = null;
	}

	function startEditConfig(trait: string) {
		editingTrait = editingTrait === trait ? null : trait;
		configKey = '';
		configValue = '';
	}

	function addConfigEntry(trait: string) {
		if (!configKey.trim()) return;
		const config = { ...workingTraits[trait] };
		// Try to parse value as JSON, fall back to string
		let parsed: unknown;
		try {
			parsed = JSON.parse(configValue);
		} catch {
			parsed = configValue;
		}
		config[configKey.trim()] = parsed;
		workingTraits = { ...workingTraits, [trait]: config };
		configKey = '';
		configValue = '';
	}

	function removeConfigEntry(trait: string, key: string) {
		const config = { ...workingTraits[trait] };
		delete config[key];
		workingTraits = { ...workingTraits, [trait]: config };
	}

	function handleDedicatedConfigChange(trait: string, newConfig: Record<string, unknown>) {
		workingTraits = { ...workingTraits, [trait]: newConfig };
	}

	async function save() {
		isSaving = true;
		error = null;
		successMsg = null;

		try {
			const newMetadata = { ...metadata, traits: workingTraits };
			await updateNode(accessToken, {
				node_id: collectionId,
				metadata: newMetadata,
			});
			successMsg = 'Traits oppdatert';
			// Auto-clear success message
			setTimeout(() => { successMsg = null; }, 2000);
		} catch (e) {
			error = e instanceof Error ? e.message : 'Ukjent feil';
		} finally {
			isSaving = false;
		}
	}
</script>

<div class="rounded-lg border border-gray-200 bg-white shadow-sm">
	<!-- Header -->
	<div class="flex items-center justify-between border-b border-gray-200 px-4 py-3">
		<h2 class="text-sm font-semibold text-gray-900">Administrer traits</h2>
		<button
			onclick={onclose}
			class="text-sm text-gray-400 hover:text-gray-600"
		>
			Lukk
		</button>
	</div>

	<div class="p-4">
		<!-- Active traits -->
		{#if activeTraitNames.length > 0}
			<div class="mb-4">
				<h3 class="mb-2 text-xs font-semibold tracking-wide text-gray-400 uppercase">
					Aktive traits ({activeTraitNames.length})
				</h3>
				<div class="space-y-2">
					{#each activeTraitNames as trait (trait)}
						<div class="rounded-lg border border-gray-100 bg-gray-50 px-3 py-2">
							<div class="flex items-center justify-between">
								<div class="flex items-center gap-2">
									<span class="text-sm font-medium text-gray-800">{trait}</span>
									{#if Object.keys(workingTraits[trait]).length > 0}
										<span class="text-[10px] text-gray-400">
											({Object.keys(workingTraits[trait]).length} config)
										</span>
									{/if}
								</div>
								<div class="flex items-center gap-1">
									<button
										onclick={() => startEditConfig(trait)}
										class="rounded px-2 py-0.5 text-xs text-gray-500 hover:bg-gray-200 hover:text-gray-700"
									>
										{editingTrait === trait ? 'Skjul' : 'Config'}
									</button>
									<button
										onclick={() => removeTrait(trait)}
										class="rounded px-2 py-0.5 text-xs text-red-500 hover:bg-red-50 hover:text-red-700"
									>
										Fjern
									</button>
								</div>
							</div>

							<!-- Per-trait config editor -->
							{#if editingTrait === trait}
								<div class="mt-2 border-t border-gray-200 pt-2">
									{#if trait === 'podcast'}
										<!-- Dedicated podcast config UI -->
										<PodcastTraitAdmin
											config={workingTraits[trait]}
											onchange={(c) => handleDedicatedConfigChange(trait, c)}
										/>
									{:else}
										<!-- Generic key-value editor -->
										{#each Object.entries(workingTraits[trait]) as [key, value] (key)}
											<div class="flex items-center justify-between py-1">
												<span class="text-xs text-gray-600">
													<span class="font-mono font-medium">{key}</span>: {JSON.stringify(value)}
												</span>
												<button
													onclick={() => removeConfigEntry(trait, key)}
													class="text-[10px] text-red-400 hover:text-red-600"
												>
													slett
												</button>
											</div>
										{/each}

										<!-- Add new config entry -->
										<div class="mt-1 flex gap-1">
											<input
												type="text"
												bind:value={configKey}
												placeholder="Nøkkel"
												class="w-28 rounded border border-gray-300 px-2 py-1 text-xs focus:border-indigo-500 focus:outline-none"
											/>
											<input
												type="text"
												bind:value={configValue}
												placeholder="Verdi"
												class="flex-1 rounded border border-gray-300 px-2 py-1 text-xs focus:border-indigo-500 focus:outline-none"
											/>
											<button
												onclick={() => addConfigEntry(trait)}
												disabled={!configKey.trim()}
												class="rounded bg-gray-100 px-2 py-1 text-xs text-gray-600 hover:bg-gray-200 disabled:opacity-50"
											>
												Legg til
											</button>
										</div>
									{/if}
								</div>
							{/if}
						</div>
					{/each}
				</div>
			</div>
		{/if}

		<!-- Add traits from catalog -->
		<div class="mb-4">
			<h3 class="mb-2 text-xs font-semibold tracking-wide text-gray-400 uppercase">
				Legg til traits
			</h3>
			<div class="space-y-3">
				{#each traitCatalog as category (category.label)}
					{@const availableTraits = category.traits.filter(t => !(t in workingTraits))}
					{#if availableTraits.length > 0}
						<div>
							<h4 class="mb-1 text-[11px] font-medium text-gray-500">{category.label}</h4>
							<div class="flex flex-wrap gap-1">
								{#each availableTraits as trait (trait)}
									<button
										onclick={() => addTrait(trait)}
										class="rounded-full border border-gray-200 bg-white px-2.5 py-0.5 text-xs text-gray-600 hover:border-indigo-300 hover:bg-indigo-50 hover:text-indigo-700"
									>
										+ {trait}
									</button>
								{/each}
							</div>
						</div>
					{/if}
				{/each}
			</div>
		</div>

		<!-- Status messages -->
		{#if error}
			<div class="mb-3 rounded border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
				{error}
			</div>
		{/if}
		{#if successMsg}
			<div class="mb-3 rounded border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700">
				{successMsg}
			</div>
		{/if}

		<!-- Save button -->
		<div class="flex items-center justify-end gap-2 border-t border-gray-100 pt-3">
			<button
				onclick={onclose}
				class="rounded-lg px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-100"
			>
				Avbryt
			</button>
			<button
				onclick={save}
				disabled={!hasChanges() || isSaving}
				class="rounded-lg bg-indigo-600 px-4 py-1.5 text-sm font-medium text-white hover:bg-indigo-700 disabled:cursor-not-allowed disabled:opacity-50"
			>
				{#if isSaving}
					Lagrer...
				{:else}
					Lagre endringer
				{/if}
			</button>
		</div>
	</div>
</div>
