<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';
	import { snackSuccess, snackError } from '$lib/stores/snackbar.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');
			snackError(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();
			snackSuccess(t('snack.serverSaved'));
		} catch (err: any) { error = err.message; snackError(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(); snackSuccess(t('snack.serverDeleted')); } catch (err: any) { error = err.message; snackError(err.message); }
	}
</script>

<PageHeader title={t('servers.title')} description={t('servers.description')}>
	<button onclick={() => { showForm ? (showForm = false, editing = null) : openNew(); }}
		class="header-action-btn"
		style="background: {showForm ? 'var(--color-muted)' : 'var(--color-primary)'}; color: {showForm ? 'var(--color-foreground)' : 'var(--color-primary-foreground)'};">
		{#if showForm}
			<MdiIcon name="mdiClose" size={14} />
			{t('servers.cancel')}
		{:else}
			<MdiIcon name="mdiPlus" size={14} />
			{t('servers.addServer')}
		{/if}
	</button>
</PageHeader>

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

{#if loadError}
	<Card class="mb-6">
		<div class="flex items-center gap-2 text-sm" style="color: var(--color-error-fg);">
			<MdiIcon name="mdiAlertCircle" size={18} />
			{loadError}
		</div>
	</Card>
{/if}

{#if showForm}
	<div in:slide={{ duration: 200 }}>
	<Card class="mb-6">
		{#if error}
			<div class="flex items-center gap-2 text-sm rounded-lg p-3 mb-4" style="background: var(--color-error-bg); color: var(--color-error-fg);">
				<MdiIcon name="mdiAlertCircle" size={16} />
				{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-lg 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-lg 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-lg text-sm bg-[var(--color-background)]" />
			</div>
			<button type="submit" disabled={submitting}
				class="form-submit-btn">
				{#if submitting}
					<div class="w-4 h-4 rounded-full border-2 border-current border-t-transparent animate-spin"></div>
				{/if}
				{submitting ? t('servers.connecting') : (editing ? t('common.save') : t('servers.addServer'))}
			</button>
		</form>
	</Card>
	</div>
{/if}

{#if servers.length === 0 && !showForm}
	<Card>
		<div class="flex flex-col items-center py-8 gap-3" style="color: var(--color-muted-foreground);">
			<div style="opacity: 0.4;"><MdiIcon name="mdiServerOff" size={40} /></div>
			<p class="text-sm">{t('servers.noServers')}</p>
		</div>
	</Card>
{:else}
	<div class="space-y-3 stagger-children">
		{#each servers as server}
			<Card hover>
				<div class="flex items-center justify-between">
					<div class="flex items-center gap-3">
						<div class="health-dot {health[server.id] === true ? 'online' : health[server.id] === false ? 'offline' : 'checking'}"></div>
						{#if server.icon}
							<span style="color: var(--color-primary);"><MdiIcon name={server.icon} size={20} /></span>
						{/if}
						<div>
							<p class="font-medium">{server.name}</p>
							<p class="text-sm font-mono" style="color: var(--color-muted-foreground); font-size: 0.75rem;">{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} />

<style>
	.header-action-btn {
		display: flex;
		align-items: center;
		gap: 0.375rem;
		padding: 0.5rem 1rem;
		border-radius: 0.625rem;
		font-size: 0.8rem;
		font-weight: 500;
		border: none;
		cursor: pointer;
		transition: all 0.2s ease;
	}

	.header-action-btn:hover {
		box-shadow: 0 0 16px var(--color-glow);
		transform: translateY(-1px);
	}

	.form-submit-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 0.5rem;
		padding: 0.5rem 1.25rem;
		border-radius: 0.625rem;
		font-size: 0.875rem;
		font-weight: 500;
		border: none;
		background: var(--color-primary);
		color: var(--color-primary-foreground);
		cursor: pointer;
		transition: all 0.2s ease;
	}

	.form-submit-btn:hover:not(:disabled) {
		box-shadow: 0 0 16px var(--color-glow-strong);
		transform: translateY(-1px);
	}

	.form-submit-btn:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}

	.health-dot {
		width: 10px;
		height: 10px;
		border-radius: 50%;
		flex-shrink: 0;
		transition: all 0.3s ease;
	}

	.health-dot.online {
		background: #059669;
		box-shadow: 0 0 8px rgba(5, 150, 105, 0.4);
	}

	.health-dot.offline {
		background: #ef4444;
		box-shadow: 0 0 8px rgba(239, 68, 68, 0.3);
	}

	.health-dot.checking {
		background: #f59e0b;
		animation: pulseCheck 1.5s ease-in-out infinite;
	}

	@keyframes pulseCheck {
		0%, 100% { box-shadow: 0 0 4px rgba(245, 158, 11, 0.3); }
		50% { box-shadow: 0 0 12px rgba(245, 158, 11, 0.6); }
	}
</style>
