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

	let loading = $state(true);
	let saving = $state(false);
	let testing = $state(false);
	let npmUrl = $state('');
	let npmEmail = $state('');
	let npmPassword = $state('');
	let npmHasCredentials = $state(false);
	let editingNpm = $state(false);
	let errors = $state<Record<string, string>>({});

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

	function validateNpmForm(): boolean {
		const newErrors: Record<string, string> = {};
		if (!npmUrl.trim()) { newErrors.npmUrl = $t('validation.required', { field: 'NPM URL' }); } else { try { new URL(npmUrl.trim()); } catch { newErrors.npmUrl = $t('validation.invalidUrl'); } }
		if (!npmEmail.trim()) { newErrors.npmEmail = $t('validation.required', { field: 'Email' }); } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(npmEmail.trim())) { newErrors.npmEmail = $t('validation.invalidEmail'); }
		if (editingNpm && !npmPassword.trim()) { newErrors.npmPassword = $t('validation.requiredWhenUpdating', { field: 'Password' }); }
		errors = newErrors;
		return Object.keys(newErrors).length === 0;
	}

	async function loadData() {
		loading = true;
		try {
			const settings = await getSettings();
			npmUrl = settings.npm_url ?? '';
			npmEmail = settings.npm_email ?? '';
			npmHasCredentials = !!(settings.npm_url && settings.npm_email);
			npmPassword = '';
			sslCertificateId = settings.ssl_certificate_id ?? 0;
			if (sslCertificateId > 0) sslCertName = `Certificate #${sslCertificateId}`;
		} catch (err) { toasts.error(err instanceof Error ? err.message : $t('settingsCredentials.loadFailed')); } finally { loading = false; }
	}

	async function handleTestConnection() {
		if (!validateNpmForm()) return;
		testing = true;
		try {
			await testNpmConnection({
				npm_url: npmUrl.trim(),
				npm_email: npmEmail.trim(),
				npm_password: npmPassword.trim() || undefined
			});
			toasts.success($t('settingsNpm.testSuccess'));
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('settingsNpm.testFailed'));
		} finally { testing = false; }
	}

	async function handleSaveNpm() {
		if (!validateNpmForm()) return;
		saving = true;
		try {
			// Validate connection before saving.
			await testNpmConnection({
				npm_url: npmUrl.trim(),
				npm_email: npmEmail.trim(),
				npm_password: npmPassword.trim() || undefined
			});
		} catch (err) {
			toasts.error($t('settingsNpm.saveFailedConnection') + ': ' + (err instanceof Error ? err.message : ''));
			saving = false;
			return;
		}
		try {
			const payload: Record<string, unknown> = { npm_url: npmUrl.trim(), npm_email: npmEmail.trim() };
			if (npmPassword.trim()) payload.npm_password = npmPassword.trim();
			await updateSettings(payload);
			npmHasCredentials = true;
			editingNpm = false;
			npmPassword = '';
			toasts.success($t('settingsCredentials.saved'));
		} catch (err) { toasts.error(err instanceof Error ? err.message : $t('settingsCredentials.saveFailed')); } finally { saving = false; }
	}

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

	async function saveCertificate(id: number) {
		try { await updateSettings({ ssl_certificate_id: id }); toasts.success($t('settingsCredentials.saved')); }
		catch (err) { toasts.error(err instanceof Error ? err.message : $t('settingsCredentials.saveFailed')); }
	}

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

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

	async function resolveCertName() {
		if (sslCertificateId <= 0) return;
		try {
			const certs = await listNpmCertificates();
			const match = certs.find((c) => c.id === sslCertificateId);
			sslCertName = match ? (match.nice_name || `Certificate #${match.id}`) : `Certificate #${sslCertificateId}`;
		} catch { sslCertName = `Certificate #${sslCertificateId}`; }
	}

	async function init() { await loadData(); await resolveCertName(); }
	$effect(() => { init(); });
</script>

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

<div class="space-y-6">
	<div>
		<h2 class="text-lg font-semibold text-[var(--text-primary)]">{$t('settings.npm')}</h2>
		<p class="text-sm text-[var(--text-secondary)]">{$t('settingsCredentials.npmDesc')}</p>
	</div>

	{#if loading}
		<div class="space-y-4"><Skeleton height="12rem" /></div>
	{:else}
		<!-- NPM Credentials -->
		<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 shadow-[var(--shadow-sm)]">
			<div class="flex items-center justify-between mb-4">
				<h3 class="text-sm font-semibold text-[var(--text-primary)]">{$t('settingsCredentials.npm')}</h3>
				{#if npmHasCredentials && !editingNpm}
					<span class="inline-flex items-center gap-1 rounded-full bg-emerald-50 dark:bg-emerald-950/30 px-2.5 py-0.5 text-xs font-medium text-emerald-700 dark:text-emerald-400">
						<IconCheck size={12} />
						{$t('settingsCredentials.configured')}
					</span>
				{/if}
			</div>

			{#if !editingNpm && npmHasCredentials}
				<div class="space-y-2">
					{#each [{ label: $t('settingsCredentials.npmUrl'), value: npmUrl }, { label: $t('settingsCredentials.email'), value: npmEmail }, { label: $t('settingsCredentials.password'), value: '--------' }] as item}
						<div class="flex items-center justify-between rounded-lg bg-[var(--surface-card-hover)] px-4 py-2.5">
							<div>
								<p class="text-xs font-medium text-[var(--text-tertiary)]">{item.label}</p>
								<p class="text-sm text-[var(--text-secondary)] {item.label === $t('settingsCredentials.password') ? 'font-mono' : ''}">{item.value || $t('settingsCredentials.notSet')}</p>
							</div>
						</div>
					{/each}
					<button onclick={() => { editingNpm = true; }} class="mt-3 inline-flex items-center gap-2 rounded-lg border border-[var(--border-primary)] px-4 py-2 text-sm font-medium text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)] transition-colors">
						<IconEdit size={16} />
						{$t('settingsCredentials.changeCredentials')}
					</button>
				</div>
			{:else}
				<div class="space-y-4">
					<FormField label={$t('settingsCredentials.npmUrl')} name="npmUrl" bind:value={npmUrl} placeholder="http://npm:81" required error={errors.npmUrl ?? ''} helpText={$t('settingsCredentials.npmUrlHelp')} />
					<FormField label={$t('settingsCredentials.email')} name="npmEmail" type="email" bind:value={npmEmail} placeholder="admin@example.com" required error={errors.npmEmail ?? ''} helpText={$t('settingsCredentials.emailHelp')} />
					<FormField label={$t('settingsCredentials.password')} name="npmPassword" type="password" bind:value={npmPassword} placeholder={npmHasCredentials ? '(enter new password)' : 'npm-password'} required={editingNpm} error={errors.npmPassword ?? ''} helpText={npmHasCredentials ? $t('settingsCredentials.passwordHelpEdit') : $t('settingsCredentials.passwordHelpNew')} />
					<div class="flex gap-3">
						<button onclick={handleSaveNpm} disabled={saving || testing} 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 saving}<IconLoader size={16} />{/if}
							{saving ? $t('settingsCredentials.saving') : $t('settingsCredentials.save')}
						</button>
						<button onclick={handleTestConnection} disabled={testing || saving} class="inline-flex items-center gap-2 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)] disabled:opacity-50 transition-colors active:animate-press">
							{#if testing}<IconLoader size={16} />{:else}<IconWifi size={16} />{/if}
							{testing ? $t('settingsNpm.testing') : $t('settingsNpm.testConnection')}
						</button>
						{#if npmHasCredentials}
							<button onclick={() => { editingNpm = false; npmPassword = ''; errors = {}; }} 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>
						{/if}
					</div>
				</div>
			{/if}
		</div>

		<!-- SSL Certificate -->
		<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 shadow-[var(--shadow-sm)]">
			<div class="flex items-start gap-3">
				<div class="flex-1">
					<h3 class="text-sm font-semibold text-[var(--text-primary)]">{$t('settingsGeneral.sslCertificate')}</h3>
					<p class="mt-0.5 text-xs text-[var(--text-tertiary)]">{$t('settingsGeneral.sslCertificateHelp')}</p>
					<div class="mt-3 flex items-center gap-2">
						<button type="button" onclick={openCertPicker} disabled={loadingCerts}
							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 disabled:opacity-50">
							<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>
	{/if}
</div>

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