<script lang="ts">
	import { onMount } from 'svelte';
	import { slide } from 'svelte/transition';
	import { api } from '$lib/api';
	import { t } from '$lib/i18n';
	import PageHeader from '$lib/components/PageHeader.svelte';
	import Card from '$lib/components/Card.svelte';
	import Loading from '$lib/components/Loading.svelte';
	import IconPicker from '$lib/components/IconPicker.svelte';
	import MdiIcon from '$lib/components/MdiIcon.svelte';
	import ConfirmModal from '$lib/components/ConfirmModal.svelte';
	import IconButton from '$lib/components/IconButton.svelte';

	let servers = $state<any[]>([]);
	let showForm = $state(false);
	let editing = $state<number | null>(null);
	let form = $state({ name: 'Immich', url: '', api_key: '', icon: '' });
	let error = $state('');
	let loadError = $state('');
	let submitting = $state(false);
	let loaded = $state(false);
	let confirmDelete = $state<any>(null);

	let health = $state<Record<number, boolean | null>>({});

	onMount(load);
	async function load() {
		try {
			servers = await api('/servers');
			loadError = '';
		} catch (err: any) {
			loadError = err.message || t('servers.loadError');
		} finally { loaded = true; }
		// Ping all servers in background
		for (const s of servers) {
			health[s.id] = null; // loading
			api(`/servers/${s.id}/ping`).then(r => health[s.id] = r.online).catch(() => health[s.id] = false);
		}
	}

	function openNew() {
		form = { name: 'Immich', url: '', api_key: '', icon: '' };
		editing = null; showForm = true;
	}
	function edit(s: any) {
		form = { name: s.name, url: s.url, api_key: '', icon: s.icon || '' };
		editing = s.id; showForm = true;
	}

	async function save(e: SubmitEvent) {
		e.preventDefault(); error = ''; submitting = true;
		try {
			if (editing) {
				const body: any = { name: form.name, url: form.url };
				if (form.api_key) body.api_key = form.api_key;
				await api(`/servers/${editing}`, { method: 'PUT', body: JSON.stringify(body) });
			} else {
				await api('/servers', { method: 'POST', body: JSON.stringify(form) });
			}
			showForm = false; editing = null; await load();
		} catch (err: any) { error = err.message; }
		submitting = false;
	}

	function startDelete(server: any) {
		confirmDelete = server;
	}

	async function doDelete() {
		if (!confirmDelete) return;
		const id = confirmDelete.id;
		confirmDelete = null;
		try { await api(`/servers/${id}`, { method: 'DELETE' }); await load(); } catch (err: any) { error = err.message; }
	}
</script>

<PageHeader title={t('servers.title')} description={t('servers.description')}>
	<button onclick={() => { showForm ? (showForm = false, editing = null) : openNew(); }}
		class="px-3 py-1.5 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded-md text-sm font-medium hover:opacity-90">
		{#if showForm}
			{t('servers.cancel')}
		{:else}
			<span class="flex items-center gap-1"><MdiIcon name="mdiPlus" size={14} />{t('servers.addServer')}</span>
		{/if}
	</button>
</PageHeader>

{#if !loaded}
	<Loading />
{:else}

{#if loadError}
	<Card class="mb-6">
		<div class="bg-[var(--color-error-bg)] text-[var(--color-error-fg)] text-sm rounded-md p-3">{loadError}</div>
	</Card>
{/if}

{#if showForm}
	<div in:slide={{ duration: 200 }}>
	<Card class="mb-6">
		{#if error}<div class="bg-[var(--color-error-bg)] text-[var(--color-error-fg)] text-sm rounded-md p-3 mb-4">{error}</div>{/if}
		<form onsubmit={save} class="space-y-3">
			<div>
				<div class="flex items-end gap-2">
					<label for="srv-name" class="block text-sm font-medium mb-1">{t('servers.name')}</label>
				</div>
				<div class="flex gap-2">
					<IconPicker value={form.icon} onselect={(v) => form.icon = v} />
					<input id="srv-name" bind:value={form.name} required class="flex-1 px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
				</div>
			</div>
			<div>
				<label for="srv-url" class="block text-sm font-medium mb-1">{t('servers.url')}</label>
				<input id="srv-url" bind:value={form.url} required placeholder={t('servers.urlPlaceholder')} class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
			</div>
			<div>
				<label for="srv-key" class="block text-sm font-medium mb-1">{editing ? t('servers.apiKeyKeep') : t('servers.apiKey')}</label>
				<input id="srv-key" bind:value={form.api_key} type="password" required={!editing} class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
			</div>
			<button type="submit" disabled={submitting} class="px-4 py-2 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50">
				{submitting ? t('servers.connecting') : (editing ? t('common.save') : t('servers.addServer'))}
			</button>
		</form>
	</Card>
	</div>
{/if}

{#if servers.length === 0 && !showForm}
	<Card><p class="text-sm text-[var(--color-muted-foreground)]">{t('servers.noServers')}</p></Card>
{:else}
	<div class="space-y-3">
		{#each servers as server}
			<Card hover>
				<div class="flex items-center justify-between">
					<div class="flex items-center gap-2">
						<span class="inline-block w-2.5 h-2.5 rounded-full {health[server.id] === true ? 'bg-green-500' : health[server.id] === false ? 'bg-red-500' : 'bg-yellow-400 animate-pulse'}"
							title={health[server.id] === true ? t('servers.online') : health[server.id] === false ? t('servers.offline') : t('servers.checking')}></span>
						{#if server.icon}<MdiIcon name={server.icon} />{/if}
						<div>
							<p class="font-medium">{server.name}</p>
							<p class="text-sm text-[var(--color-muted-foreground)]">{server.url}</p>
						</div>
					</div>
					<div class="flex items-center gap-1">
						<IconButton icon="mdiPencil" title={t('common.edit')} onclick={() => edit(server)} />
						<IconButton icon="mdiDelete" title={t('common.delete')} onclick={() => startDelete(server)} variant="danger" />
					</div>
				</div>
			</Card>
		{/each}
	</div>
{/if}

{/if}

<ConfirmModal open={!!confirmDelete} title={t('common.delete')} message={t('servers.confirmDelete')}
	onconfirm={doDelete} oncancel={() => confirmDelete = null} />
