<script lang="ts">
	import { getSettings, updateSettings, getWebhookUrl, regenerateWebhookUrl, testDnsConnection, listDnsZones } 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, IconX, IconInfo } 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');


	// Proxy provider state.
	let proxyProvider = $state('npm');

	// DNS settings state.
	let wildcardDns = $state(true);
	let dnsProvider = $state('');
	let cloudflareApiToken = $state('');
	let hasCloudflareApiToken = $state(false);
	let cloudflareZoneId = $state('');
	let zonePickerOpen = $state(false);
	let zonePickerItems = $state<EntityPickerItem[]>([]);
	let loadingZones = $state(false);
	let zoneName = $state('');
	let testingDns = $state(false);

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

	function validateDomain(value: string): string {
		if (!value.trim()) return '';
		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 | number): string {
		const s = String(value ?? '');
		if (!s.trim()) return '';
		const num = parseInt(s, 10);
		if (isNaN(num) || num < 60 || 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 ?? '';
			notificationUrl = settings.notification_url ?? '';
			staleThresholdDays = String(settings.stale_threshold_days ?? 7);
			proxyProvider = settings.proxy_provider ?? 'npm';
			wildcardDns = settings.wildcard_dns ?? true;
			dnsProvider = settings.dns_provider ?? '';
			hasCloudflareApiToken = settings.has_cloudflare_api_token ?? false;
			cloudflareZoneId = settings.cloudflare_zone_id ?? '';
		} 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.webhook_url;
		} catch { /* may not be configured */ }
	}

	async function handleSave() {
		if (!validateAll()) return;
		saving = true;
		try {
			const payload: Record<string, unknown> = {
				domain: domain.trim(), server_ip: serverIp.trim(), network: network.trim(),
				subdomain_pattern: subdomainPattern.trim(), polling_interval: String(pollingInterval ?? '').trim(),
				base_volume_path: baseVolumePath.trim(), notification_url: notificationUrl.trim(),
				proxy_provider: proxyProvider,
				stale_threshold_days: Math.max(1, parseInt(staleThresholdDays, 10) || 7),
				wildcard_dns: wildcardDns,
				dns_provider: wildcardDns ? '' : dnsProvider,
				cloudflare_zone_id: cloudflareZoneId
			};
			if (cloudflareApiToken) {
				payload.cloudflare_api_token = cloudflareApiToken;
			}
			await updateSettings(payload as any);
			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.webhook_url;
			toasts.success($t('settingsGeneral.regenerated'));
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.regenerateFailed'));
		} finally {
			regenerating = false;
		}
	}


	async function openZonePicker() {
		loadingZones = true;
		zonePickerOpen = true;
		try {
			const token = cloudflareApiToken || undefined;
			const zones = await listDnsZones(token);
			zonePickerItems = zones.map((zone): EntityPickerItem => ({
				value: zone.id,
				label: zone.name,
				description: zone.id
			}));
			if (zonePickerItems.length === 0) {
				toasts.error($t('settingsGeneral.noZonesFound'));
				zonePickerOpen = false;
			}
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.noZonesFound'));
			zonePickerOpen = false;
		} finally {
			loadingZones = false;
		}
	}

	function handleZoneSelect(value: string) {
		cloudflareZoneId = value;
		const item = zonePickerItems.find((i) => i.value === value);
		zoneName = item?.label ?? '';
		zonePickerOpen = false;
	}

	async function handleTestDns() {
		testingDns = true;
		try {
			const token = cloudflareApiToken || '';
			const result = await testDnsConnection('cloudflare', token, cloudflareZoneId);
			if (result.success) {
				toasts.success($t('settingsGeneral.connectionSuccess'));
			} else {
				toasts.error(`${$t('settingsGeneral.connectionFailed')}: ${result.error}`);
			}
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.connectionFailed'));
		} finally {
			testingDns = false;
		}
	}

	async function resolveZoneName() {
		if (!cloudflareZoneId) return;
		try {
			const zones = await listDnsZones();
			const match = zones.find((z) => z.id === cloudflareZoneId);
			zoneName = match?.name ?? cloudflareZoneId;
		} catch {
			zoneName = cloudflareZoneId;
		}
	}

	async function init() {
		await loadSettings();
		if (!wildcardDns && cloudflareZoneId) {
			resolveZoneName();
		}
		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" 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')} />
				<div>
					<div class="flex items-center gap-1.5">
						<label for="subdomainPattern" class="block text-sm font-medium text-[var(--text-primary)]">{$t('settingsGeneral.subdomainPattern')}</label>
						<div class="group relative">
							<button type="button" class="inline-flex items-center justify-center rounded-full text-[var(--text-tertiary)] hover:text-[var(--text-secondary)] transition-colors" aria-label={$t('settingsGeneral.subdomainVarsTitle')}>
								<IconInfo size={14} />
							</button>
							<div class="pointer-events-none absolute bottom-full left-1/2 z-50 mb-2 w-64 -translate-x-1/2 rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card)] p-3 shadow-lg opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100">
								<p class="mb-2 text-xs font-semibold text-[var(--text-primary)]">{$t('settingsGeneral.subdomainVarsTitle')}</p>
								<ul class="space-y-1 text-xs text-[var(--text-secondary)]">
									<li><code class="rounded bg-[var(--surface-card-hover)] px-1 py-0.5 font-mono text-[var(--text-link)]">{'{project}'}</code> — {$t('settingsGeneral.varProject')}</li>
									<li><code class="rounded bg-[var(--surface-card-hover)] px-1 py-0.5 font-mono text-[var(--text-link)]">{'{stage}'}</code> — {$t('settingsGeneral.varStage')}</li>
									<li><code class="rounded bg-[var(--surface-card-hover)] px-1 py-0.5 font-mono text-[var(--text-link)]">{'{tag}'}</code> — {$t('settingsGeneral.varTag')}</li>
									<li><code class="rounded bg-[var(--surface-card-hover)] px-1 py-0.5 font-mono text-[var(--text-link)]">{'{port}'}</code> — {$t('settingsGeneral.varPort')}</li>
								</ul>
								<div class="absolute left-1/2 top-full -translate-x-1/2 border-4 border-transparent border-t-[var(--border-primary)]"></div>
							</div>
						</div>
					</div>
					<input
						id="subdomainPattern"
						type="text"
						bind:value={subdomainPattern}
						placeholder="stage-{'{stage}'}-{'{project}'}"
						class="mt-1.5 block w-full rounded-lg border border-[var(--border-input)] bg-[var(--surface-input)] px-3 py-2 text-sm text-[var(--text-primary)] placeholder:text-[var(--text-tertiary)] focus:border-[var(--color-brand-500)] focus:outline-none focus:ring-1 focus:ring-[var(--color-brand-500)]"
					/>
					<p class="mt-1 text-xs text-[var(--text-tertiary)]">{$t('settingsGeneral.subdomainPatternHelp')}</p>
				</div>
				<FormField label={$t('settingsGeneral.pollingInterval')} name="pollingInterval" type="number" bind:value={pollingInterval} placeholder="60" error={errors.pollingInterval ?? ''} helpText={$t('settingsGeneral.pollingIntervalHelp')} />
				<FormField label={$t('settingsGeneral.baseVolumePath')} name="baseVolumePath" bind:value={baseVolumePath} placeholder="/data" helpText={$t('settingsGeneral.baseVolumePathHelp')} />
				<FormField label={$t('settingsGeneral.notificationUrl')} name="notificationUrl" bind:value={notificationUrl} placeholder="https://notify.example.com/webhook" error={errors.notificationUrl ?? ''} helpText={$t('settingsGeneral.notificationUrlHelp')} />
			</div>
			<!-- Proxy Provider -->
			<div class="mt-6 border-t border-[var(--border-primary)] pt-4">
				<h3 class="mb-1 text-sm font-semibold text-[var(--text-primary)]">{$t('settings.proxyProvider')}</h3>
				<p class="mb-3 text-xs text-[var(--text-tertiary)]">{$t('settings.proxyProviderHelp')}</p>
				<div class="flex gap-3">
					<label class="flex flex-1 cursor-pointer items-start gap-3 rounded-lg border p-3 transition-colors {proxyProvider === 'none' ? 'border-[var(--color-brand-500)] bg-[var(--surface-card-hover)]' : 'border-[var(--border-primary)] hover:bg-[var(--surface-card-hover)]'}">
						<input type="radio" bind:group={proxyProvider} value="none" class="mt-0.5 h-4 w-4 text-[var(--color-brand-600)] focus:ring-[var(--color-brand-500)]" />
						<div>
							<span class="text-sm font-medium text-[var(--text-primary)]">{$t('settings.proxyNone')}</span>
							<p class="text-xs text-[var(--text-tertiary)]">{$t('settings.proxyNoneDesc')}</p>
						</div>
					</label>
					<label class="flex flex-1 cursor-pointer items-start gap-3 rounded-lg border p-3 transition-colors {proxyProvider === 'npm' ? 'border-[var(--color-brand-500)] bg-[var(--surface-card-hover)]' : 'border-[var(--border-primary)] hover:bg-[var(--surface-card-hover)]'}">
						<input type="radio" bind:group={proxyProvider} value="npm" class="mt-0.5 h-4 w-4 text-[var(--color-brand-600)] focus:ring-[var(--color-brand-500)]" />
						<div>
							<span class="text-sm font-medium text-[var(--text-primary)]">{$t('settings.proxyNpm')}</span>
							<p class="text-xs text-[var(--text-tertiary)]">{$t('settings.proxyNpmDesc')}</p>
						</div>
					</label>
					<label class="flex flex-1 cursor-pointer items-start gap-3 rounded-lg border p-3 transition-colors {proxyProvider === 'traefik' ? 'border-[var(--color-brand-500)] bg-[var(--surface-card-hover)]' : 'border-[var(--border-primary)] hover:bg-[var(--surface-card-hover)]'}">
						<input type="radio" bind:group={proxyProvider} value="traefik" class="mt-0.5 h-4 w-4 text-[var(--color-brand-600)] focus:ring-[var(--color-brand-500)]" />
						<div>
							<span class="text-sm font-medium text-[var(--text-primary)]">{$t('settings.proxyTraefik')}</span>
							<p class="text-xs text-[var(--text-tertiary)]">{$t('settings.proxyTraefikDesc')}</p>
						</div>
					</label>
				</div>
				{#if proxyProvider === 'none'}
					<div class="mt-3 rounded-lg border border-amber-300 bg-amber-50 dark:border-amber-700 dark:bg-amber-950/30 p-3">
						<p class="text-sm text-amber-800 dark:text-amber-300">{$t('settings.proxyNoneWarning')}</p>
					</div>
				{/if}
			</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>

			<!-- DNS Configuration -->
			<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('settingsGeneral.dnsConfig')}</h3>

				<label class="flex items-center gap-3 cursor-pointer">
					<input type="checkbox" bind:checked={wildcardDns}
						class="h-4 w-4 rounded border-[var(--border-primary)] text-[var(--color-brand-600)] focus:ring-[var(--color-brand-500)]" />
					<div>
						<span class="text-sm font-medium text-[var(--text-primary)]">{$t('settingsGeneral.wildcardDns')}</span>
						<p class="text-xs text-[var(--text-tertiary)]">{$t('settingsGeneral.wildcardDnsHelp')}</p>
					</div>
				</label>

				{#if !wildcardDns}
					<div class="mt-4 space-y-4 rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card-hover)] p-4">
						<!-- DNS Provider -->
						<div>
							<label for="dnsProvider" class="block text-sm font-medium text-[var(--text-primary)]">{$t('settingsGeneral.dnsProvider')}</label>
							<p class="mt-0.5 text-xs text-[var(--text-tertiary)]">{$t('settingsGeneral.dnsProviderHelp')}</p>
							<select id="dnsProvider" bind:value={dnsProvider}
								class="mt-1.5 w-full max-w-xs rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card)] px-3 py-2 text-sm text-[var(--text-primary)] focus:border-[var(--color-brand-500)] focus:outline-none focus:ring-1 focus:ring-[var(--color-brand-500)]">
								<option value="">-- Select --</option>
								<option value="cloudflare">Cloudflare</option>
							</select>
						</div>

						{#if dnsProvider === 'cloudflare'}
							<!-- Cloudflare API Token -->
							<div>
								<FormField
									label={$t('settingsGeneral.cloudflareApiToken')}
									name="cloudflareApiToken"
									type="password"
									bind:value={cloudflareApiToken}
									placeholder={hasCloudflareApiToken ? '••••••••' : $t('settingsGeneral.cloudflareApiTokenPlaceholder')}
									helpText={hasCloudflareApiToken ? $t('settingsGeneral.cloudflareApiTokenConfigured') : $t('settingsGeneral.cloudflareApiTokenHelp')}
								/>
							</div>

							<!-- Zone Picker -->
							<div>
								<label for="cloudflareZoneBtn" class="block text-sm font-medium text-[var(--text-primary)]">{$t('settingsGeneral.cloudflareZone')}</label>
								<p class="mt-0.5 text-xs text-[var(--text-tertiary)]">{$t('settingsGeneral.cloudflareZoneHelp')}</p>
								<div class="mt-1.5 flex items-center gap-2">
									<button
										id="cloudflareZoneBtn"
										type="button"
										onclick={openZonePicker}
										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)] transition-colors"
									>
										{#if loadingZones}
											{$t('settingsGeneral.loadingZones')}
										{:else if cloudflareZoneId && zoneName}
											{zoneName}
										{:else}
											{$t('settingsGeneral.noZone')}
										{/if}
									</button>
									{#if cloudflareZoneId}
										<button
											type="button"
											onclick={() => { cloudflareZoneId = ''; zoneName = ''; }}
											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)] transition-colors"
										>
											<IconX size={14} />
										</button>
									{/if}
								</div>
							</div>

							<!-- Test Connection -->
							<div>
								<button
									type="button"
									onclick={handleTestDns}
									disabled={testingDns || (!cloudflareApiToken && !hasCloudflareApiToken)}
									class="inline-flex items-center gap-2 rounded-lg border border-[var(--color-brand-600)] px-3 py-2 text-sm font-medium text-[var(--color-brand-600)] hover:bg-[var(--color-brand-50)] transition-colors disabled:opacity-50"
								>
									{#if testingDns}<IconLoader size={16} />{/if}
									{testingDns ? $t('settingsGeneral.testingConnection') : $t('settingsGeneral.testConnection')}
								</button>
							</div>
						{/if}
					</div>
				{/if}
			</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={zonePickerOpen}
	items={zonePickerItems}
	current={cloudflareZoneId}
	title={$t('settingsGeneral.selectZone')}
	onselect={handleZoneSelect}
	onclose={() => { zonePickerOpen = false; }}
/>
