<script lang="ts">
	import { listRegistries, createRegistry, updateRegistry, deleteRegistry, testRegistry } from '$lib/api';
	import type { Registry } from '$lib/types';
	import FormField from '$lib/components/FormField.svelte';
	import EmptyState from '$lib/components/EmptyState.svelte';
	import Skeleton from '$lib/components/Skeleton.svelte';
	import { toasts } from '$lib/stores/toast';
	import { t } from '$lib/i18n';
	import { IconPlus, IconLoader, IconEdit, IconTrash, IconWifi } from '$lib/components/icons';
	import ConfirmDialog from '$lib/components/ConfirmDialog.svelte';

	let registries = $state<Registry[]>([]);
	let loading = $state(true);

	let showForm = $state(false);
	let editingId = $state<string | null>(null);
	let formName = $state('');
	let formUrl = $state('');
	let formType = $state('gitea');
	let formToken = $state('');
	let formOwner = $state('');
	let formSaving = $state(false);
	let testingId = $state<string | null>(null);
	let healthStatus = $state<Record<string, 'checking' | 'healthy' | 'unhealthy'>>({});

	let registryDeleteTarget = $state<Registry | null>(null);
	let errors = $state<Record<string, string>>({});

	function validateForm(): boolean {
		const newErrors: Record<string, string> = {};
		if (!formName.trim()) newErrors.name = $t('validation.required', { field: 'Name' });
		if (!formUrl.trim()) { newErrors.url = $t('validation.required', { field: 'URL' }); } else { try { new URL(formUrl.trim()); } catch { newErrors.url = $t('validation.invalidUrl'); } }
		if (!formToken.trim() && !editingId) newErrors.token = $t('validation.requiredForNew', { field: 'Token' });
		errors = newErrors;
		return Object.keys(newErrors).length === 0;
	}

	function resetForm() { showForm = false; editingId = null; formName = ''; formUrl = ''; formType = 'gitea'; formToken = ''; formOwner = ''; errors = {}; }
	function startEdit(registry: Registry) { editingId = registry.id; formName = registry.name; formUrl = registry.url; formType = registry.type; formToken = ''; formOwner = registry.owner ?? ''; showForm = true; errors = {}; }

	async function loadRegistryList() {
		loading = true;
		try {
			registries = await listRegistries();
			// Check health of all registries in the background.
			checkAllHealth();
		} catch (err) { toasts.error(err instanceof Error ? err.message : $t('settingsRegistries.loadFailed')); } finally { loading = false; }
	}

	async function handleSave() {
		if (!validateForm()) return;
		formSaving = true;
		try {
			const payload: Partial<Registry> = { name: formName.trim(), url: formUrl.trim(), type: formType, owner: formOwner.trim() };
			if (formToken.trim()) payload.token = formToken.trim();
			if (editingId) { await updateRegistry(editingId, payload); toasts.success($t('settingsRegistries.registryUpdated')); }
			else { await createRegistry(payload); toasts.success($t('settingsRegistries.registryAdded')); }
			resetForm();
			await loadRegistryList();
		} catch (err) { toasts.error(err instanceof Error ? err.message : $t('settingsRegistries.saveFailed')); } finally { formSaving = false; }
	}

	async function handleDelete(registry: Registry) {
		try { await deleteRegistry(registry.id); toasts.success($t('settingsRegistries.registryDeleted', { name: registry.name })); await loadRegistryList(); }
		catch (err) { toasts.error(err instanceof Error ? err.message : $t('settingsRegistries.deleteFailed')); }
	}

	async function handleTestConnection(registry: Registry) {
		testingId = registry.id;
		try {
			await testRegistry(registry.id);
			toasts.success($t('settingsRegistries.testSuccess', { name: registry.name }));
			healthStatus[registry.id] = 'healthy';
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('settingsRegistries.testFailed'));
			healthStatus[registry.id] = 'unhealthy';
		} finally { testingId = null; }
	}

	async function checkAllHealth() {
		for (const reg of registries) {
			healthStatus[reg.id] = 'checking';
			try {
				await testRegistry(reg.id);
				healthStatus[reg.id] = 'healthy';
			} catch {
				healthStatus[reg.id] = 'unhealthy';
			}
		}
	}

	$effect(() => { loadRegistryList(); });
</script>

<svelte:head>
	<title>{$t('settingsRegistries.title')} - {$t('app.name')}</title>
</svelte:head>

<div class="space-y-6">
	<div class="flex items-center justify-between">
		<div>
			<h2 class="text-lg font-semibold text-[var(--text-primary)]">{$t('settingsRegistries.title')}</h2>
			<p class="text-sm text-[var(--text-secondary)]">{$t('settingsRegistries.description')}</p>
		</div>
		{#if !showForm}
			<button onclick={() => { resetForm(); showForm = true; }} class="inline-flex items-center gap-2 rounded-lg bg-[var(--color-brand-600)] px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-[var(--color-brand-700)] transition-colors active:animate-press">
				<IconPlus size={16} />
				{$t('settingsRegistries.addRegistry')}
			</button>
		{/if}
	</div>

	{#if showForm}
		<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 animate-scale-in">
			<h3 class="mb-4 text-sm font-semibold text-[var(--text-primary)]">
				{editingId ? $t('settingsRegistries.editRegistry') : $t('settingsRegistries.addNewRegistry')}
			</h3>
			<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
				<FormField label={$t('settingsRegistries.name')} name="registryName" bind:value={formName} placeholder="gitea" required error={errors.name ?? ''} helpText={$t('settingsRegistries.nameHelp')} />
				<FormField label={$t('settingsRegistries.url')} name="registryUrl" bind:value={formUrl} placeholder="https://git.example.com" required error={errors.url ?? ''} helpText={$t('settingsRegistries.urlHelp')} />
				<div class="flex flex-col gap-1.5">
					<label for="registryType" class="text-sm font-medium text-[var(--text-primary)]">{$t('settingsRegistries.type')}</label>
					<select id="registryType" bind:value={formType} class="rounded-lg border border-[var(--border-input)] bg-[var(--surface-input)] px-3 py-2 text-sm text-[var(--text-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-brand-500)]">
						<option value="gitea">Gitea</option>
						<option value="github">GitHub</option>
						<option value="docker_hub">Docker Hub</option>
						<option value="custom">Custom</option>
					</select>
					<p class="text-xs text-[var(--text-tertiary)]">{$t('settingsRegistries.typeHelp')}</p>
				</div>
				<FormField label={$t('settingsRegistries.token')} name="registryToken" type="password" bind:value={formToken} placeholder={editingId ? '(leave empty to keep current)' : 'registry-access-token'} required={!editingId} error={errors.token ?? ''} helpText={editingId ? $t('settingsRegistries.tokenHelpEdit') : $t('settingsRegistries.tokenHelpNew')} />
					<FormField label={$t('settingsRegistries.owner')} name="registryOwner" bind:value={formOwner} placeholder="alexei" helpText={$t('settingsRegistries.ownerHelp')} />
			</div>
			<div class="mt-4 flex gap-3">
				<button onclick={handleSave} disabled={formSaving} class="inline-flex items-center gap-2 rounded-lg bg-[var(--color-brand-600)] px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-[var(--color-brand-700)] disabled:opacity-50 transition-colors active:animate-press">
					{#if formSaving}<IconLoader size={16} />{/if}
					{formSaving ? $t('settingsRegistries.saving') : editingId ? $t('settingsRegistries.update') : $t('settingsRegistries.addRegistry')}
				</button>
				<button onclick={resetForm} disabled={formSaving} class="rounded-lg border border-[var(--border-primary)] px-4 py-2.5 text-sm font-medium text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)] transition-colors">
					{$t('common.cancel')}
				</button>
			</div>
		</div>
	{/if}

	{#if loading}
		<div class="space-y-3">
			{#each Array(2) as _}
				<Skeleton height="5rem" />
			{/each}
		</div>
	{:else if registries.length === 0}
		<EmptyState title={$t('empty.noRegistries')} description={$t('empty.noRegistriesDesc')} actionLabel={$t('settingsRegistries.addFirst')} onaction={() => { showForm = true; }} icon="registries" />
	{:else}
		<div class="space-y-3">
			{#each registries as registry (registry.id)}
				<div class="flex items-center justify-between rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-4 shadow-[var(--shadow-sm)] transition-all duration-150 hover:shadow-[var(--shadow-md)]">
					<div>
						<div class="flex items-center gap-2">
							{#if healthStatus[registry.id] === 'checking'}
								<span class="h-2.5 w-2.5 shrink-0 rounded-full bg-yellow-400 animate-pulse" title="Checking..."></span>
							{:else if healthStatus[registry.id] === 'healthy'}
								<span class="h-2.5 w-2.5 shrink-0 rounded-full bg-emerald-500" title="Connected"></span>
							{:else if healthStatus[registry.id] === 'unhealthy'}
								<span class="h-2.5 w-2.5 shrink-0 rounded-full bg-red-500" title="Unreachable"></span>
							{/if}
							<h3 class="text-sm font-semibold text-[var(--text-primary)]">{registry.name}</h3>
							<span class="rounded-full bg-[var(--surface-card-hover)] px-2 py-0.5 text-xs font-medium text-[var(--text-tertiary)]">{registry.type}</span>
						</div>
						<p class="mt-1 text-sm text-[var(--text-secondary)]">{registry.url}{registry.owner ? `/${registry.owner}` : ''}</p>
					</div>
					<div class="flex items-center gap-2">
						<button onclick={() => handleTestConnection(registry)} disabled={testingId === registry.id} class="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border-primary)] px-3 py-1.5 text-xs font-medium text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)] disabled:opacity-50 transition-colors">
							{#if testingId === registry.id}<IconLoader size={14} />{:else}<IconWifi size={14} />{/if}
							{testingId === registry.id ? $t('settingsRegistries.testing') : $t('settingsRegistries.test')}
						</button>
						<button onclick={() => startEdit(registry)} class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-[var(--surface-card-hover)] hover:text-[var(--text-link)] transition-colors"><IconEdit size={16} /></button>
						<button onclick={() => { registryDeleteTarget = registry; }} class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-red-50 hover:text-red-600 transition-colors"><IconTrash size={16} /></button>
					</div>
				</div>
			{/each}
		</div>
	{/if}
</div>

<ConfirmDialog
	open={registryDeleteTarget !== null}
	title={$t('settingsRegistries.deleteTitle')}
	message={$t('settingsRegistries.deleteConfirm', { name: registryDeleteTarget?.name ?? '' })}
	confirmLabel={$t('common.delete')}
	confirmVariant="danger"
	onconfirm={async () => {
		const reg = registryDeleteTarget;
		registryDeleteTarget = null;
		if (reg) await handleDelete(reg);
	}}
	oncancel={() => { registryDeleteTarget = null; }}
/>
