<script lang="ts">
	import { onMount } from 'svelte';
	import { fetchSettings, updateSetting } from '$lib/api';
	import type { Settings } from '$lib/api';
	import { writable } from 'svelte/store';
	import CodeMirror from 'svelte-codemirror-editor';

	let settings = writable<Settings[]>([]);
	let isLoading = writable(false);
	let error = writable<string | null>(null);

	async function loadSettings() {
		isLoading.set(true);
		error.set(null);
		try {
			const data = await fetchSettings();
			settings.set(data);
		} catch (err) {
			error.set('Failed to load settings');
		} finally {
			isLoading.set(false);
		}
	}

	async function saveSetting(setting: Settings) {
		isLoading.set(true);
		error.set(null);
		try {
			await updateSetting(setting.id, setting);
			loadSettings(); // Refresh settings after update
		} catch (err) {
			error.set('Failed to save setting');
		} finally {
			isLoading.set(false);
		}
	}

	onMount(() => {
		loadSettings();
	});
</script>

<div class="container mx-auto p-4">
	<h1 class="text-2xl font-bold mb-4">Settings</h1>

	{#if $isLoading}
		<p>Loading...</p>
	{:else if $error}
		<p class="text-red-500">{$error}</p>
	{:else}
		<div class="space-y-4">
			{#each $settings as setting (setting.id)}
				<div class="p-4 border rounded shadow">
					<label class="block mb-2 font-bold">
						Requirements
						<div class="w-full border rounded">
							<CodeMirror bind:value={setting.requirements} />
						</div>
					</label>

					<label class="block mt-4 mb-2 font-bold">
						Environment
						<div class="w-full border rounded">
							<CodeMirror bind:value={setting.environment} />
						</div>
					</label>

					<label class="block mt-4 mb-2 font-bold">
						Ntfy URL
						<input
							type="text"
							class="w-full p-2 border rounde font-normal"
							bind:value={setting.ntfy_url}
						/>
					</label>

					<button
						class="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
						on:click={() => saveSetting(setting)}
					>
						Save
					</button>
				</div>
			{/each}
		</div>
	{/if}
</div>

<style>
	.container {
		max-width: 800px;
	}
</style>
