<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import * as api from '$lib/api';
	import type { MetricAlertRule, MetricAlertRuleInput } from '$lib/api';
	import { metricAlertRuleDetailCache } from '$lib/stores/caches';
	import ForgeHero from '$lib/components/ForgeHero.svelte';
	import ToggleSwitch from '$lib/components/ToggleSwitch.svelte';
	import ConfirmDialog from '$lib/components/ConfirmDialog.svelte';
	import { t } from '$lib/i18n';

	// SvelteKit gives a string id; a non-numeric path silently maps
	// to NaN. Guard explicitly so the rest of the page doesn't make
	// bogus API calls.
	const id = $derived.by(() => {
		const n = Number($page.params.id);
		return Number.isFinite(n) && n > 0 ? n : null;
	});

	let rule = $state<MetricAlertRule | null>(null);
	let loading = $state(true);
	let saving = $state(false);
	let deleting = $state(false);
	let confirmDelete = $state(false);
	let error = $state('');
	// Cached workload name for the scope label. We fetch by id
	// rather than listing every workload because the rule already
	// tells us exactly which one to look up. A failed lookup falls
	// back to the truncated id so the page still renders.
	let scopedWorkloadName = $state('');

	let name = $state('');
	let metric = $state<'cpu_percent' | 'memory_percent' | 'memory_bytes'>('cpu_percent');
	let comparator = $state<'gt' | 'lt'>('gt');
	// Threshold is held as a string so an empty field is distinguishable
	// from 0; submit sends Number(threshold) and is blocked when NaN.
	let threshold = $state('');
	let severity = $state<'info' | 'warn' | 'error'>('warn');
	let cooldownSeconds = $state(60);
	let enabled = $state(true);

	const thresholdNum = $derived.by(() => {
		const n = Number(threshold);
		return threshold.trim() !== '' && Number.isFinite(n) ? n : null;
	});

	// Units hint under the threshold field swaps with the selected
	// metric: percent metrics read "%", memory_bytes reads "bytes".
	const thresholdHint = $derived(
		metric === 'memory_bytes'
			? $t('metricalert.form.thresholdHintBytes')
			: $t('metricalert.form.thresholdHintPercent')
	);

	function seedForm(r: MetricAlertRule): void {
		name = r.name;
		metric = r.metric;
		comparator = r.comparator;
		threshold = String(r.threshold);
		severity = r.severity;
		cooldownSeconds = r.cooldown_seconds;
		enabled = r.enabled;
	}

	// Best-effort scope-label resolution (fire-and-forget); failure falls back
	// to the truncated id. Runs once per id alongside the form seed.
	async function resolveScopeName(r: MetricAlertRule, k: string): Promise<void> {
		if (!r.workload_id) {
			scopedWorkloadName = '';
			return;
		}
		try {
			const w = await api.getWorkload(r.workload_id);
			// Ignore a late response if we've since navigated to another id.
			if (String(id) === k) scopedWorkloadName = w.name;
		} catch {
			if (String(id) === k) scopedWorkloadName = '';
		}
	}

	// Keyed warm-seed: render the cached rule instantly on revisit and seed the
	// editable form ONCE per id (a background revalidation never re-seeds, so
	// unsaved edits survive). Plain (non-reactive) so the $effect tracks only id.
	let seededKey: string | null = null;

	async function load(): Promise<void> {
		if (id === null) {
			error = 'Invalid rule id';
			loading = false;
			return;
		}
		const k = String(id);
		const cached = metricAlertRuleDetailCache.peek(k);
		if (cached.value) {
			rule = cached.value;
			if (seededKey !== k) { seedForm(cached.value); resolveScopeName(cached.value, k); seededKey = k; }
			loading = false;
		} else {
			loading = true;
		}
		error = '';
		await metricAlertRuleDetailCache.refresh(k);
		// Bail if the route id changed while we were fetching — a newer load()
		// now owns the page state; applying this stale result would clobber it.
		if (id === null || String(id) !== k) return;
		const entry = metricAlertRuleDetailCache.peek(k);
		if (entry.error && !cached.value) {
			error = entry.error || 'Failed to load rule';
			loading = false;
			return;
		}
		if (entry.value) {
			rule = entry.value;
			if (seededKey !== k) { seedForm(entry.value); resolveScopeName(entry.value, k); seededKey = k; }
		}
		loading = false;
	}

	async function save(e?: Event): Promise<void> {
		e?.preventDefault();
		if (!rule || id === null || saving || thresholdNum === null) return;
		saving = true;
		error = '';
		try {
			const body: MetricAlertRuleInput = {
				name: name.trim(),
				metric,
				comparator,
				threshold: thresholdNum,
				severity,
				cooldown_seconds: cooldownSeconds,
				enabled
			};
			rule = await api.updateMetricAlertRule(id, body);
			metricAlertRuleDetailCache.set(String(id), rule);
		} catch (e) {
			error = e instanceof Error ? e.message : 'Save failed';
		} finally {
			saving = false;
		}
	}

	async function doDelete(): Promise<void> {
		if (id === null) return;
		deleting = true;
		error = '';
		try {
			await api.deleteMetricAlertRule(id);
			goto('/metric-alert-rules');
		} catch (e) {
			error = e instanceof Error ? e.message : 'Delete failed';
			deleting = false;
			confirmDelete = false;
		}
	}

	function scopeLabel(r: MetricAlertRule | null): string {
		if (!r) return '';
		if (r.workload_id !== '') {
			// Prefer the human-readable name when the workload load
			// succeeded; fall back to the truncated id so the label
			// still resolves on missing/deleted workloads.
			const label = scopedWorkloadName || r.workload_id.slice(0, 8);
			return $t('metricalert.scope.workload', { id: label });
		}
		return $t('metricalert.scope.global');
	}

	// Reload when route id changes — SvelteKit reuses the component
	// instance across [id] transitions, so onMount alone would leave
	// stale data when navigating between sibling pages.
	$effect(() => {
		const _ = id;
		load();
	});
</script>

<svelte:head>
	<title>{rule?.name ?? $t('metricalert.titleSingular')} · Tinyforge</title>
</svelte:head>

<div class="forge" aria-busy={loading}>
	{#snippet detailLede()}
		{#if rule}
			<span class="lede-meta">
				{$t('metricalert.list.scope')} <code>{scopeLabel(rule)}</code> ·
				{$t('metricalert.list.severity')} <code>{rule.severity}</code>
			</span>
		{/if}
	{/snippet}

	<ForgeHero
		backHref="/metric-alert-rules"
		backLabel={$t('metricalert.toolbar.backToList')}
		eyebrowSuffix={$t('metricalert.titleSingular').toUpperCase()}
		title={rule?.name ?? $t('observability.loading')}
		size="lg"
		lede_html={rule ? detailLede : undefined}
	/>

	{#if error}
		<div class="alert" role="alert">
			<span class="alert-tag">ERR</span><span>{error}</span>
		</div>
	{/if}

	{#if loading || !rule}
		<div class="skeleton-rows" aria-busy="true" aria-live="polite" aria-label={$t('observability.loading')}>
			{#each Array(3) as _, i}
				<div class="skeleton-row" style:--i={i}></div>
			{/each}
		</div>
	{:else}
		<form class="panel" onsubmit={save} aria-busy={saving}>
			<header class="panel-head">
				<h2 class="panel-title">{$t('metricalert.detail.config')}<span class="title-accent">.</span></h2>
				<span class="panel-sub">
					{$t('metricalert.detail.configSub', { id: String(rule.id), scope: scopeLabel(rule) })}
				</span>
			</header>

			<div class="field">
				<label for="r-name" class="sub-label">{$t('metricalert.form.name')}</label>
				<input id="r-name" type="text" class="input" bind:value={name} required />
			</div>

			<div class="row three">
				<label class="sub" for="r-metric">
					<span class="sub-label">{$t('metricalert.form.metric')}</span>
					<select id="r-metric" class="input" bind:value={metric}>
						<option value="cpu_percent">{$t('metricalert.metric.cpu_percent')}</option>
						<option value="memory_percent">{$t('metricalert.metric.memory_percent')}</option>
						<option value="memory_bytes">{$t('metricalert.metric.memory_bytes')}</option>
					</select>
				</label>
				<label class="sub" for="r-comparator">
					<span class="sub-label">{$t('metricalert.form.comparator')}</span>
					<select id="r-comparator" class="input" bind:value={comparator}>
						<option value="gt">{$t('metricalert.comparator.gt')}</option>
						<option value="lt">{$t('metricalert.comparator.lt')}</option>
					</select>
				</label>
				<label class="sub" for="r-threshold">
					<span class="sub-label">{$t('metricalert.form.threshold')}</span>
					<input
						id="r-threshold"
						type="number"
						min="0"
						step="any"
						class="input"
						bind:value={threshold}
						required
					/>
				</label>
			</div>
			<p class="hint">{thresholdHint}</p>

			<div class="row three">
				<label class="sub" for="r-severity">
					<span class="sub-label">{$t('metricalert.form.severity')}</span>
					<select id="r-severity" class="input" bind:value={severity}>
						<option value="info">info</option>
						<option value="warn">warn</option>
						<option value="error">error</option>
					</select>
				</label>
				<label class="sub" for="r-cooldown">
					<span class="sub-label">{$t('metricalert.form.cooldown')}</span>
					<input
						id="r-cooldown"
						type="number"
						min="0"
						class="input"
						bind:value={cooldownSeconds}
					/>
				</label>
			</div>

			<div class="row-toggle">
				<div class="toggle-copy">
					<span class="lbl" aria-hidden="true">{$t('metricalert.form.enabled')}</span>
					<p class="hint">{$t('metricalert.form.enabledHint')}</p>
				</div>
				<ToggleSwitch bind:checked={enabled} label={$t('metricalert.form.enabled')} />
			</div>

			<div class="actions">
				<button
					type="submit"
					class="forge-btn"
					disabled={saving || !name.trim() || thresholdNum === null}
					aria-busy={saving}
				>
					{saving ? $t('observability.saving') : $t('observability.save')}
				</button>
			</div>
		</form>

		<section class="panel danger-panel" aria-labelledby="danger-heading">
			<header class="panel-head">
				<h2 class="panel-title" id="danger-heading">{$t('metricalert.detail.dangerZone')}<span class="title-accent">.</span></h2>
				<span class="panel-sub">{$t('metricalert.detail.dangerZoneSub')}</span>
			</header>
			<div class="danger-actions">
				<button
					type="button"
					class="forge-btn-ghost forge-btn-danger"
					onclick={() => (confirmDelete = true)}
				>
					{$t('metricalert.detail.deleteButton')}
				</button>
			</div>
		</section>

		<ConfirmDialog
			open={confirmDelete}
			title={$t('metricalert.detail.deleteTitle')}
			message={$t('metricalert.detail.deleteMessage', { name: name.trim() || rule.name })}
			confirmLabel={deleting ? $t('observability.deleting') : $t('observability.delete')}
			confirmVariant="danger"
			onconfirm={doDelete}
			oncancel={() => (confirmDelete = false)}
		/>
	{/if}
</div>

<style>
	.forge {
		display: flex;
		flex-direction: column;
		gap: 1.25rem;
		max-width: 820px;
		margin: 0 auto;
	}

	/* ── Alert ─────────────────────────────────────── */
	.alert {
		display: flex;
		gap: 0.7rem;
		align-items: center;
		padding: 0.7rem 0.9rem;
		background: var(--color-danger-light);
		color: var(--color-danger-dark);
		border: 1px solid var(--color-danger);
		border-left-width: 4px;
		border-radius: var(--radius-lg);
		font-size: 0.875rem;
	}
	.alert-tag {
		font-family: var(--forge-mono);
		font-weight: 700;
		font-size: 0.65rem;
		letter-spacing: 0.16em;
		padding: 0.15rem 0.4rem;
		background: var(--color-danger);
		color: var(--surface-card);
		border-radius: var(--radius-sm);
	}
	:global([data-theme='dark']) .alert {
		background: color-mix(in srgb, var(--color-danger) 14%, transparent);
		color: color-mix(in srgb, var(--color-danger) 60%, var(--text-primary));
	}

	/* ── Skeleton ──────────────────────────────────── */
	.skeleton-rows {
		display: flex;
		flex-direction: column;
		gap: 0.55rem;
	}
	.skeleton-row {
		height: 64px;
		border: 1px solid var(--border-primary);
		border-radius: var(--radius-2xl);
		background: linear-gradient(
			110deg,
			var(--surface-card) 20%,
			var(--surface-card-hover) 50%,
			var(--surface-card) 80%
		);
		background-size: 200% 100%;
		animation: shimmer 1.6s linear infinite;
		animation-delay: calc(var(--i) * 120ms);
	}
	@keyframes shimmer {
		0% {
			background-position: 200% 0;
		}
		100% {
			background-position: -200% 0;
		}
	}

	/* ── Panel ─────────────────────────────────────── */
	.panel {
		display: flex;
		flex-direction: column;
		gap: 0.9rem;
		background: var(--surface-card);
		border: 1px solid var(--border-primary);
		border-radius: var(--radius-2xl);
		padding: 1.5rem;
	}
	@media (max-width: 600px) {
		.panel {
			padding: 1.1rem;
			gap: 1rem;
		}
	}
	.panel.danger-panel {
		border-color: color-mix(in srgb, var(--color-danger) 35%, var(--border-primary));
	}
	.panel-head {
		display: flex;
		flex-direction: column;
		gap: 0.25rem;
		margin-bottom: 0.2rem;
	}
	.panel-title {
		margin: 0;
		font-size: 1.1rem;
		font-weight: 700;
		letter-spacing: -0.01em;
		color: var(--text-primary);
	}
	.title-accent {
		color: var(--forge-accent);
	}
	.panel-sub {
		font-family: var(--forge-mono);
		font-size: 0.7rem;
		color: var(--text-tertiary);
		line-height: 1.5;
	}

	/* ── Fields ────────────────────────────────────── */
	.field {
		display: flex;
		flex-direction: column;
		gap: 0.35rem;
	}
	.sub-label {
		font-family: var(--forge-mono);
		font-size: 0.62rem;
		font-weight: 600;
		letter-spacing: 0.14em;
		text-transform: uppercase;
		color: var(--text-secondary);
	}
	.input {
		width: 100%;
		background: var(--surface-input);
		border: 1px solid var(--border-input);
		border-radius: var(--radius-lg);
		padding: 0.55rem 0.75rem;
		font-size: 0.9rem;
		color: var(--text-primary);
		font-family: inherit;
		outline: none;
		transition: border-color 120ms ease, box-shadow 120ms ease;
	}
	.input:focus {
		border-color: var(--border-focus);
		box-shadow: 0 0 0 3px var(--forge-accent-soft);
	}

	.row.three {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr;
		gap: 0.9rem;
	}
	@media (max-width: 720px) {
		.row.three {
			grid-template-columns: 1fr 1fr;
		}
	}
	@media (max-width: 480px) {
		.row.three {
			grid-template-columns: 1fr;
		}
	}
	.sub {
		display: flex;
		flex-direction: column;
		gap: 0.35rem;
		min-width: 0;
	}

	/* ── Hints ──────────────────────────────────────── */
	.hint {
		font-size: 0.78rem;
		color: var(--text-tertiary);
		line-height: 1.5;
		margin: 0;
	}

	/* ── Toggle row ─────────────────────────────────── */
	.row-toggle {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		gap: 1rem;
		padding-top: 0.5rem;
		border-top: 1px dashed var(--border-primary);
		margin-top: 0.2rem;
	}
	.toggle-copy {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 0.25rem;
	}
	.lbl {
		font-weight: 600;
		font-size: 0.95rem;
		color: var(--text-primary);
	}

	/* ── Action footers ─────────────────────────────── */
	.actions {
		display: flex;
		justify-content: flex-end;
		gap: 0.55rem;
		padding-top: 0.4rem;
		flex-wrap: wrap;
	}
	.danger-actions {
		display: flex;
		justify-content: flex-end;
	}
	@media (max-width: 480px) {
		.actions {
			flex-direction: column-reverse;
			align-items: stretch;
		}
		.actions :global(.forge-btn),
		.actions :global(.forge-btn-ghost) {
			justify-content: center;
		}
		.danger-actions :global(.forge-btn-ghost) {
			width: 100%;
			justify-content: center;
		}
	}
</style>
