<script lang="ts">
	import { getSettings, updateSettings } from '$lib/api';
	import FormField from '$lib/components/FormField.svelte';
	import Skeleton from '$lib/components/Skeleton.svelte';
	import { toasts } from '$lib/stores/toast';
	import { t } from '$lib/i18n';
	import { IconLoader, IconCheck, IconEdit } from '$lib/components/icons';

	let loading = $state(true);
	let saving = $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>>({});

	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 loadCredentials() {
		loading = true;
		try {
			const settings = await getSettings();
			npmUrl = settings.npm_url ?? '';
			npmEmail = settings.npm_email ?? '';
			npmHasCredentials = !!(settings.npm_url && settings.npm_email);
			npmPassword = '';
		} catch (err) { toasts.error(err instanceof Error ? err.message : $t('settingsCredentials.loadFailed')); } finally { loading = false; }
	}

	async function handleSaveNpm() {
		if (!validateNpmForm()) return;
		saving = true;
		try {
			const payload: Record<string, string> = { 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; }
	}

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

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

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

	{#if loading}
		<div class="space-y-4"><Skeleton height="12rem" /></div>
	{:else}
		<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">
				<div>
					<h3 class="text-sm font-semibold text-[var(--text-primary)]">{$t('settingsCredentials.npm')}</h3>
					<p class="text-xs text-[var(--text-tertiary)]">{$t('settingsCredentials.npmDesc')}</p>
				</div>
				{#if npmHasCredentials && !editingNpm}
					<span class="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2.5 py-0.5 text-xs font-medium text-emerald-700">
						<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 || 'Not set'}</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} 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>
						{#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>

		<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 shadow-[var(--shadow-sm)]">
			<h3 class="text-sm font-semibold text-[var(--text-primary)]">{$t('settingsCredentials.registryTokens')}</h3>
			<p class="mt-1 text-sm text-[var(--text-secondary)]">
				{$t('settingsCredentials.registryTokensDesc')}
				<a href="/settings/registries" class="text-[var(--text-link)] hover:text-[var(--text-link-hover)] underline transition-colors">{$t('settingsCredentials.registriesLink')}</a>
				{$t('settingsCredentials.registryTokensSuffix')}
			</p>
		</div>
	{/if}
</div>
