<script lang="ts">
	import { getSettings, updateSettings, getWebhookUrl, regenerateWebhookUrl, listNpmCertificates } from '$lib/api';
	import type { EntityPickerItem } from '$lib/types';
	import FormField from '$lib/components/FormField.svelte';
	import EntityPicker from '$lib/components/EntityPicker.svelte';
	import { toasts } from '$lib/stores/toast';
	import { t } from '$lib/i18n';
	import { IconLoader, IconCopy, IconRefresh, IconShield, IconX } from '$lib/components/icons';
	import Skeleton from '$lib/components/Skeleton.svelte';

	let loading = $state(true);
	let saving = $state(false);
	let webhookUrl = $state('');
	let regenerating = $state(false);

	let domain = $state('');
	let serverIp = $state('');
	let network = $state('');
	let subdomainPattern = $state('');
	let pollingInterval = $state('');
	let baseVolumePath = $state('');
	let notificationUrl = $state('');
	let staleThresholdDays = $state('7');

	let sslCertificateId = $state(0);
	let sslCertName = $state('');
	let certPickerOpen = $state(false);
	let certPickerItems = $state<EntityPickerItem[]>([]);
	let loadingCerts = $state(false);

	let errors = $state<Record<string, string>>({});

	function validateDomain(value: string): string {
		if (!value.trim()) return $t('validation.required', { field: 'Domain' });
		if (!/^[a-zA-Z0-9][a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/.test(value.trim())) return $t('validation.invalidDomain');
		return '';
	}

	function validateIp(value: string): string {
		if (!value.trim()) return '';
		if (!/^(\d{1,3}\.){3}\d{1,3}$/.test(value.trim())) return $t('validation.invalidIp');
		return '';
	}

	function validatePollingInterval(value: string): string {
		if (!value.trim()) return '';
		const num = parseInt(value, 10);
		if (isNaN(num) || num < 10 || num > 86400) return $t('validation.invalidPollingInterval');
		return '';
	}

	function validateUrl(value: string): string {
		if (!value.trim()) return '';
		try { new URL(value.trim()); return ''; } catch { return $t('validation.invalidUrl'); }
	}

	function validateAll(): boolean {
		const newErrors: Record<string, string> = {};
		const domainErr = validateDomain(domain);
		if (domainErr) newErrors.domain = domainErr;
		const ipErr = validateIp(serverIp);
		if (ipErr) newErrors.serverIp = ipErr;
		const intervalErr = validatePollingInterval(pollingInterval);
		if (intervalErr) newErrors.pollingInterval = intervalErr;
		const urlErr = validateUrl(notificationUrl);
		if (urlErr) newErrors.notificationUrl = urlErr;
		errors = newErrors;
		return Object.keys(newErrors).length === 0;
	}

	async function loadSettings() {
		loading = true;
		try {
			const settings = await getSettings();
			domain = settings.domain ?? '';
			serverIp = settings.server_ip ?? '';
			network = settings.network ?? '';
			subdomainPattern = settings.subdomain_pattern ?? '';
			pollingInterval = settings.polling_interval ?? '';
			baseVolumePath = settings.base_volume_path ?? '';
			sslCertificateId = settings.ssl_certificate_id ?? 0;
			notificationUrl = settings.notification_url ?? '';
			staleThresholdDays = String(settings.stale_threshold_days ?? 7);
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.loadFailed'));
		} finally {
			loading = false;
		}
	}

	async function loadWebhookUrlValue() {
		try {
			const result = await getWebhookUrl();
			webhookUrl = result.url;
		} catch { /* may not be configured */ }
	}

	async function handleSave() {
		if (!validateAll()) return;
		saving = true;
		try {
			await updateSettings({
				domain: domain.trim(), server_ip: serverIp.trim(), network: network.trim(),
				subdomain_pattern: subdomainPattern.trim(), polling_interval: pollingInterval.trim(),
				base_volume_path: baseVolumePath.trim(), notification_url: notificationUrl.trim(),
				ssl_certificate_id: sslCertificateId,
				stale_threshold_days: Math.max(1, parseInt(staleThresholdDays, 10) || 7)
			});
			toasts.success($t('settingsGeneral.saved'));
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.saveFailed'));
		} finally {
			saving = false;
		}
	}

	async function handleRegenerateWebhook() {
		regenerating = true;
		try {
			const result = await regenerateWebhookUrl();
			webhookUrl = result.url;
			toasts.success($t('settingsGeneral.regenerated'));
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.regenerateFailed'));
		} finally {
			regenerating = false;
		}
	}

	async function openCertPicker() {
		loadingCerts = true;
		certPickerOpen = true;
		try {
			const certs = await listNpmCertificates();
			certPickerItems = certs.map((cert): EntityPickerItem => ({
				value: String(cert.id),
				label: cert.nice_name || `Certificate #${cert.id}`,
				description: cert.domain_names.join(', ')
			}));
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.noCertificatesFound'));
			certPickerOpen = false;
		} finally {
			loadingCerts = false;
		}
	}

	function handleCertSelect(value: string) {
		const id = parseInt(value, 10);
		sslCertificateId = id;
		const item = certPickerItems.find((i) => i.value === value);
		sslCertName = item?.label ?? '';
		certPickerOpen = false;
	}

	function clearCertificate() {
		sslCertificateId = 0;
		sslCertName = '';
	}

	// When loading settings, try to resolve cert name if an ID is set.
	async function resolveCertName() {
		if (sslCertificateId <= 0) return;
		try {
			const certs = await listNpmCertificates();
			const match = certs.find((c) => c.id === sslCertificateId);
			if (match) {
				sslCertName = match.nice_name || `Certificate #${match.id}`;
			} else {
				sslCertName = `Certificate #${sslCertificateId}`;
			}
		} catch {
			sslCertName = `Certificate #${sslCertificateId}`;
		}
	}

	async function init() {
		await loadSettings();
		await resolveCertName();
		loadWebhookUrlValue();
	}

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

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

<div class="space-y-6">
	{#if loading}
		<div class="space-y-4">
			<Skeleton height="2rem" width="12rem" />
			<div class="grid grid-cols-2 gap-4">
				{#each Array(6) as _}
					<Skeleton height="4rem" />
				{/each}
			</div>
		</div>
	{:else}
		<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 shadow-[var(--shadow-sm)]">
			<h2 class="mb-4 text-lg font-semibold text-[var(--text-primary)]">{$t('settingsGeneral.globalConfig')}</h2>
			<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
				<FormField label={$t('settingsGeneral.domain')} name="domain" bind:value={domain} placeholder="example.com" required error={errors.domain ?? ''} helpText={$t('settingsGeneral.domainHelp')} />
				<FormField label={$t('settingsGeneral.serverIp')} name="serverIp" bind:value={serverIp} placeholder="93.84.96.191" error={errors.serverIp ?? ''} helpText={$t('settingsGeneral.serverIpHelp')} />
				<FormField label={$t('settingsGeneral.dockerNetwork')} name="network" bind:value={network} placeholder="staging-net" helpText={$t('settingsGeneral.dockerNetworkHelp')} />
				<FormField label={$t('settingsGeneral.subdomainPattern')} name="subdomainPattern" bind:value={subdomainPattern} placeholder="stage-{'{stage}'}-{'{project}'}" helpText={$t('settingsGeneral.subdomainPatternHelp')} />
				<FormField label={$t('settingsGeneral.pollingInterval')} name="pollingInterval" type="number" bind:value={pollingInterval} placeholder="60" error={errors.pollingInterval ?? ''} helpText={$t('settingsGeneral.pollingIntervalHelp')} />
				<FormField label="Base Volume Path" name="baseVolumePath" bind:value={baseVolumePath} placeholder="/data" helpText="Prepended to relative volume sources (e.g., /data + my-app/uploads = /data/my-app/uploads)" />
				<FormField label={$t('settingsGeneral.notificationUrl')} name="notificationUrl" bind:value={notificationUrl} placeholder="https://notify.example.com/webhook" error={errors.notificationUrl ?? ''} helpText={$t('settingsGeneral.notificationUrlHelp')} />
			</div>
			<!-- SSL Certificate -->
			<div class="mt-6 border-t border-[var(--border-primary)] pt-4">
				<div class="flex items-start gap-3">
					<div class="flex-1">
						<label class="block text-sm font-medium text-[var(--text-primary)]">{$t('settingsGeneral.sslCertificate')}</label>
						<p class="mt-0.5 text-xs text-[var(--text-tertiary)]">{$t('settingsGeneral.sslCertificateHelp')}</p>
						<div class="mt-2 flex items-center gap-2">
							<button
								type="button"
								onclick={openCertPicker}
								class="inline-flex items-center gap-2 rounded-lg border border-[var(--border-primary)] px-3 py-2 text-sm text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)] transition-colors"
							>
								<IconShield size={16} />
								{#if loadingCerts}
									{$t('settingsGeneral.loadingCertificates')}
								{:else if sslCertificateId > 0 && sslCertName}
									{sslCertName}
								{:else}
									{$t('settingsGeneral.noCertificate')}
								{/if}
							</button>
							{#if sslCertificateId > 0}
								<button
									type="button"
									onclick={clearCertificate}
									class="inline-flex items-center gap-1 rounded-lg border border-[var(--border-primary)] px-2 py-2 text-sm text-[var(--text-tertiary)] hover:text-[var(--color-danger)] hover:bg-[var(--surface-card-hover)] transition-colors"
									title={$t('settingsGeneral.clearCertificate')}
								>
									<IconX size={14} />
								</button>
							{/if}
						</div>
					</div>
				</div>
			</div>

			<!-- Stale Detection -->
			<div class="mt-6 border-t border-[var(--border-primary)] pt-4">
				<h3 class="mb-3 text-sm font-semibold text-[var(--text-primary)]">{$t('stale.title')}</h3>
				<div class="max-w-xs">
					<FormField
						label={$t('settings.staleThreshold')}
						name="staleThresholdDays"
						type="number"
						bind:value={staleThresholdDays}
						placeholder="7"
						helpText={$t('settings.staleThresholdHelp')}
					/>
				</div>
			</div>

			<div class="mt-6">
				<button onclick={handleSave} disabled={saving} 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 transition-all duration-150 hover:bg-[var(--color-brand-700)] disabled:opacity-50 active:animate-press">
					{#if saving}<IconLoader size={16} />{/if}
					{saving ? $t('settingsGeneral.saving') : $t('settingsGeneral.saveSettings')}
				</button>
			</div>
		</div>

		<!-- Webhook URL -->
		<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 shadow-[var(--shadow-sm)]">
			<h2 class="mb-1 text-lg font-semibold text-[var(--text-primary)]">{$t('settingsGeneral.webhookUrl')}</h2>
			<p class="mb-3 text-sm text-[var(--text-secondary)]">{$t('settingsGeneral.webhookDesc')}</p>

			{#if webhookUrl}
				<div class="flex items-center gap-3">
					<code class="flex-1 rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card-hover)] px-3 py-2.5 font-mono text-sm text-[var(--text-secondary)] break-all">
						{webhookUrl}
					</code>
					<button
						onclick={() => { navigator.clipboard.writeText(webhookUrl); toasts.info($t('settingsGeneral.copied')); }}
						class="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border-primary)] px-3 py-2.5 text-sm font-medium text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)] transition-colors"
					>
						<IconCopy size={16} />
						{$t('settingsGeneral.copy')}
					</button>
				</div>
			{:else}
				<p class="text-sm text-[var(--text-tertiary)] italic">{$t('settingsGeneral.noWebhookUrl')}</p>
			{/if}

			<div class="mt-4">
				<button
					onclick={handleRegenerateWebhook}
					disabled={regenerating}
					class="inline-flex items-center gap-2 rounded-lg border border-[var(--color-danger)] px-4 py-2 text-sm font-medium text-[var(--color-danger)] hover:bg-[var(--color-danger-light)] transition-colors disabled:opacity-50 active:animate-press"
				>
					{#if regenerating}<IconLoader size={16} />{/if}
					<IconRefresh size={16} />
					{regenerating ? $t('settingsGeneral.regenerating') : $t('settingsGeneral.regenerateUrl')}
				</button>
				<p class="mt-1 text-xs text-[var(--text-tertiary)]">{$t('settingsGeneral.regenerateWarning')}</p>
			</div>
		</div>
	{/if}
</div>

<EntityPicker
	bind:open={certPickerOpen}
	items={certPickerItems}
	current={String(sslCertificateId)}
	title={$t('settingsGeneral.selectCertificate')}
	onselect={handleCertSelect}
	onclose={() => { certPickerOpen = false; }}
/>
