<!--
  Phase 6: Create/edit form for standalone proxies.
  Supports live destination validation with debounce.
-->
<script lang="ts">
	import type { StandaloneProxy, ValidationResult } from '$lib/types';
	import { validateProxy, createProxy, updateProxy, deleteProxy } from '$lib/api';
	import FormField from '$lib/components/FormField.svelte';
	import ValidationChecklist from '$lib/components/ValidationChecklist.svelte';
	import ConfirmDialog from '$lib/components/ConfirmDialog.svelte';
	import { IconLoader } from '$lib/components/icons';
	import { t } from '$lib/i18n';

	interface Props {
		mode: 'create' | 'edit';
		proxy?: StandaloneProxy;
		onsave?: (proxy: StandaloneProxy) => void;
		ondelete?: (id: string) => void;
		oncancel?: () => void;
	}

	const { mode, proxy, onsave, ondelete, oncancel }: Props = $props();

	// ── Form state ────────────────────────────────────────────────────
	let destinationUrl = $state(proxy?.destination_url ?? '');
	let port = $state(proxy?.destination_port?.toString() ?? '');
	let domain = $state(proxy?.domain ?? '');

	// ── Validation state ──────────────────────────────────────────────
	let validationResult: ValidationResult | null = $state(null);
	let validating = $state(false);
	let validationTimer: ReturnType<typeof setTimeout> | null = $state(null);

	// ── Submit state ──────────────────────────────────────────────────
	let submitting = $state(false);
	let submitError = $state('');

	// ── Delete state ──────────────────────────────────────────────────
	let deleteConfirmOpen = $state(false);
	let deleting = $state(false);

	// ── Derived ───────────────────────────────────────────────────────
	const portNum = $derived(parseInt(port, 10));
	const portValid = $derived(!isNaN(portNum) && portNum >= 1 && portNum <= 65535);
	const canSubmit = $derived(
		destinationUrl.trim().length > 0 &&
		port.trim().length > 0 &&
		portValid &&
		domain.trim().length > 0 &&
		!submitting
	);

	const title = $derived(
		mode === 'create' ? $t('proxies.form.title') : $t('proxies.form.editTitle')
	);

	const submitLabel = $derived(
		submitting
			? (mode === 'create' ? $t('proxies.form.create') : $t('proxies.form.save'))
			: (mode === 'create' ? $t('proxies.form.create') : $t('proxies.form.save'))
	);

	// ── Domain auto-suggestion ────────────────────────────────────────
	function suggestDomain(dest: string): string {
		if (!dest) return '';
		try {
			// If it looks like a URL, parse the hostname
			const withScheme = dest.includes('://') ? dest : `http://${dest}`;
			const url = new URL(withScheme);
			const host = url.hostname;
			// Strip common prefixes and use as subdomain suggestion
			const cleaned = host
				.replace(/^(www|api|app)\./, '')
				.replace(/\.\w+$/, '')
				.replace(/[^a-z0-9.-]/gi, '-')
				.toLowerCase();
			return cleaned || '';
		} catch {
			// If it's a plain IP or hostname, use it directly
			return dest.replace(/[^a-z0-9.-]/gi, '-').toLowerCase();
		}
	}

	// ── Live validation with debounce ─────────────────────────────────
	function scheduleValidation(): void {
		if (validationTimer !== null) {
			clearTimeout(validationTimer);
		}
		validationResult = null;

		if (!destinationUrl.trim() || !port.trim() || !portValid) {
			return;
		}

		validationTimer = setTimeout(() => {
			runValidation();
		}, 300);
	}

	async function runValidation(): Promise<void> {
		if (!destinationUrl.trim() || !portValid) return;

		validating = true;
		try {
			validationResult = await validateProxy(destinationUrl.trim(), portNum);
		} catch {
			// Validation is advisory -- don't block the UI
			validationResult = null;
		} finally {
			validating = false;
		}
	}

	function handleDestinationInput(): void {
		// Auto-suggest domain only when creating and domain is empty or was auto-generated
		if (mode === 'create') {
			const suggested = suggestDomain(destinationUrl);
			if (!domain || domain === suggestDomain(destinationUrl.slice(0, -1))) {
				domain = suggested;
			}
		}
		scheduleValidation();
	}

	function handlePortInput(): void {
		scheduleValidation();
	}

	function handleValidateClick(): void {
		if (validationTimer !== null) {
			clearTimeout(validationTimer);
		}
		runValidation();
	}

	// ── Submit ────────────────────────────────────────────────────────
	async function handleSubmit(): Promise<void> {
		if (!canSubmit) return;

		submitting = true;
		submitError = '';

		const data = {
			domain: domain.trim(),
			destination_url: destinationUrl.trim(),
			destination_port: portNum
		};

		try {
			const saved = mode === 'create'
				? await createProxy(data)
				: await updateProxy(proxy!.id, data);
			onsave?.(saved);
		} catch (err: unknown) {
			submitError = err instanceof Error ? err.message : 'Unknown error';
		} finally {
			submitting = false;
		}
	}

	// ── Delete ────────────────────────────────────────────────────────
	async function handleDeleteConfirm(): Promise<void> {
		if (!proxy) return;
		deleting = true;
		try {
			await deleteProxy(proxy.id);
			deleteConfirmOpen = false;
			ondelete?.(proxy.id);
		} catch (err: unknown) {
			submitError = err instanceof Error ? err.message : 'Unknown error';
		} finally {
			deleting = false;
		}
	}
</script>

<div class="space-y-6">
	<!-- Header -->
	<h3 class="text-lg font-semibold text-[var(--text-primary)]">{title}</h3>

	<!-- Form fields -->
	<form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="space-y-4">
		<FormField
			label={$t('proxies.form.destination')}
			name="destination_url"
			bind:value={destinationUrl}
			placeholder="192.168.1.100 or http://my-service"
			required
			oninput={handleDestinationInput}
		/>

		<FormField
			label={$t('proxies.form.port')}
			name="destination_port"
			type="number"
			bind:value={port}
			placeholder="8080"
			required
			error={port && !portValid ? $t('validation.invalidPort') : ''}
			oninput={handlePortInput}
		/>

		<FormField
			label={$t('proxies.form.domain')}
			name="domain"
			bind:value={domain}
			placeholder="my-service.example.com"
			required
			helpText={$t('proxies.form.domainHelp')}
		/>

		<!-- Validation checklist -->
		<div class="space-y-2">
			<ValidationChecklist result={validationResult} loading={validating} />

			<button
				type="button"
				class="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border-primary)] px-3 py-1.5 text-sm font-medium text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
				disabled={!destinationUrl.trim() || !portValid || validating}
				onclick={handleValidateClick}
			>
				{#if validating}
					<IconLoader size={14} />
					{$t('proxies.form.validating')}
				{:else}
					{$t('proxies.form.validate')}
				{/if}
			</button>
		</div>

		<!-- Validation warning (non-blocking) -->
		{#if validationResult && !validationResult.valid}
			<p class="text-xs text-amber-600 dark:text-amber-400">
				Validation reported issues but you can still create the proxy.
			</p>
		{/if}

		<!-- Submit error -->
		{#if submitError}
			<p class="text-sm text-[var(--color-danger)]">{submitError}</p>
		{/if}

		<!-- Action buttons -->
		<div class="flex items-center justify-between pt-2">
			<div>
				{#if mode === 'edit'}
					<button
						type="button"
						class="rounded-lg px-3 py-2 text-sm font-medium text-[var(--color-danger)] hover:bg-red-50 dark:hover:bg-red-950 transition-colors"
						onclick={() => { deleteConfirmOpen = true; }}
					>
						{$t('proxies.form.delete')}
					</button>
				{/if}
			</div>

			<div class="flex items-center gap-3">
				<button
					type="button"
					class="rounded-lg px-4 py-2 text-sm font-medium text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)] transition-colors"
					onclick={() => oncancel?.()}
				>
					{$t('proxies.form.cancel')}
				</button>

				<button
					type="submit"
					class="inline-flex items-center gap-2 rounded-lg bg-[var(--color-brand-600)] px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-[var(--color-brand-700)] transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-brand-600)] disabled:opacity-50 disabled:cursor-not-allowed"
					disabled={!canSubmit}
				>
					{#if submitting}
						<IconLoader size={14} />
					{/if}
					{submitLabel}
				</button>
			</div>
		</div>
	</form>
</div>

<!-- Delete confirmation dialog -->
{#if mode === 'edit'}
	<ConfirmDialog
		open={deleteConfirmOpen}
		title={$t('proxies.form.delete')}
		message={$t('proxies.form.deleteConfirm')}
		confirmLabel={deleting ? $t('common.loading') : $t('proxies.form.delete')}
		confirmVariant="danger"
		onconfirm={handleDeleteConfirm}
		oncancel={() => { deleteConfirmOpen = false; }}
	/>
{/if}
