<!-- #region ValidationTaskDetailPage [C:4] [TYPE Component] [SEMANTICS validation, task, detail, run-history, page] -->
<!-- @ingroup Routes -->
<!-- @BRIEF Validation task detail page with run history table, task metadata header, and action buttons (Run Now, Edit, Delete). -->
<!-- @RELATION DEPENDS_ON -> [ValidationApi] -->
<!-- @RELATION BINDS_TO -> [I18nModule] -->
<!-- @UX_STATE Loading -> Skeleton header + skeleton table rows -->
<!-- @UX_STATE Error -> Alert with error message + Retry button -->
<!-- @UX_STATE Populated -> Task header + run history table + pagination -->
<!-- @UX_STATE Empty -> Task header + "No runs yet" empty state -->
<!-- @UX_FEEDBACK Toast notifications on run/delete actions -->
<!-- @UX_RECOVERY Retry button on load errors, Back to tasks link -->
<!-- @UX_REACTIVITY Props -> $props(data), LocalState -> $state(...) -->
<script lang="ts">
	import { goto } from '$app/navigation';
	import { ROUTES } from '$lib/routes';
	import { t } from '$lib/i18n/index.svelte.js';
	import { Badge, EmptyState, Pagination, Icon } from '$lib/ui';
	import { addToast } from '$lib/toasts.svelte.js';
	import { triggerValidationRun as triggerRun, deleteValidationTask as deleteTask, getValidationRuns as fetchRuns } from '$lib/api.js';
	import { page } from '$app/state';

	/** @type {{ data: import('./$types').PageData }} */
	let { data } = $props();

	let policyId = $derived(page.params.policyId);

	/** @type {'idle'|'loading'|'populated'|'empty'|'error'} */
	// eslint-disable-next-line svelte/prefer-writable-derived
	let uxState = $state('idle');
	let task = $state(data.task);
	let runs = $state(data.runs);
	let total = $state(data.total);
	let errorMsg = $state(null);

	// Pagination
	let currentPage = $state(1);
	let pageSize = $state(20);

	// 0-indexed page for Pagination component (currentPage is 1-indexed)
	let page0 = $state(currentPage - 1);

	// Sync Pagination page changes → reload run history
	$effect(() => {
		const newPage = page0 + 1;
		if (newPage !== currentPage) {
			currentPage = newPage;
			loadRunHistory();
		}
	});

	// Action states
	let isRunning = $state(false);
	let showDeleteConfirm = $state(false);

	// Derived status
	let isScheduled = $derived(task?.schedule_days?.length > 0);



	/** @param {number} ms */
	function formatDuration(ms) {
		if (!ms && ms !== 0) return '-';
		if (ms < 1000) return `${ms}ms`;
		if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
		return `${Math.floor(ms / 60000)}m ${Math.floor((ms % 60000) / 1000)}s`;
	}

	function getAggregateSummary(run) {
		const pass = run.pass_count ?? run.passed ?? 0;
		const warn = run.warn_count ?? run.warnings ?? 0;
		const fail = run.fail_count ?? run.failed ?? 0;
		return ($t.validation?.aggregate_status || '{pass} PASS • {warn} WARN • {fail} FAIL')
			.replace('{pass}', String(pass))
			.replace('{warn}', String(warn))
			.replace('{fail}', String(fail));
	}

	function getTriggerLabel(trigger) {
		if (trigger === 'manual') return $t.validation?.trigger_manual || 'Manual';
		if (trigger === 'scheduled') return $t.validation?.trigger_scheduled || 'Scheduled';
		return trigger || '-';
	}

	async function handleRunNow() {
		isRunning = true;
		try {
			await triggerRun(policyId);
			addToast($t.validation?.run_triggered || 'Validation run triggered.', 'success');
		} catch (err) {
			addToast(err?.message || ($t.validation?.run_failed || 'Failed to trigger run.'), 'error');
		} finally {
			isRunning = false;
		}
	}

	async function handleDelete() {
		try {
			await deleteTask(policyId);
			addToast($t.validation?.delete_success || 'Deleted successfully.', 'success');
			// eslint-disable-next-line svelte/no-navigation-without-resolve
			goto(ROUTES.validationTasks.list());
		} catch (err) {
			addToast(err?.message || ($t.validation?.delete_failed || 'Failed to delete.'), 'error');
		}
	}

	async function handleEdit() {
		// eslint-disable-next-line svelte/no-navigation-without-resolve
		goto(ROUTES.validationTasks.edit(policyId));
	}

	async function loadRunHistory() {
		uxState = 'loading';
		errorMsg = null;
		try {
			const result = await fetchRuns(policyId, { page: currentPage, page_size: pageSize });
			const items = Array.isArray(result) ? result : (result?.results || result?.items || []);
			runs = items;
			total = result?.total || result?.count || items.length;
			uxState = items.length === 0 ? 'empty' : 'populated';
		} catch (err) {
			errorMsg = err?.message || ($t.validation?.load_runs_failed || 'Failed to load run history.');
			uxState = 'error';
		}
	}

	function handleViewRun(runId) {
		// eslint-disable-next-line svelte/no-navigation-without-resolve
		goto(ROUTES.validationTasks.runReport(policyId, runId));
	}

	// Initial state after load
	$effect(() => {
		uxState = data.runs.length === 0 ? 'empty' : 'populated';
	});
</script>

<svelte:head>
	<title>{task?.name || $t.validation?.run_detail || 'Task Detail'}</title>
</svelte:head>

<div class="container mx-auto px-4 py-6 max-w-full xl:max-w-7xl">
	<!-- Back link -->
	<a
		href={ROUTES.validationTasks.list()}
		class="inline-flex items-center text-sm text-text-muted hover:text-text mb-4 transition-colors"
	>
		<Icon name="chevronLeft" size={16} class="mr-1" />
		{$t.validation?.back_to_tasks || '← Back to tasks'}
	</a>

	<!-- Task Header -->
	<div class="bg-surface-card border border-border rounded-lg p-6 mb-6">
		<div class="flex items-start justify-between">
			<div class="flex-1 min-w-0">
				<div class="flex items-center gap-3 mb-2">
					<h1 class="text-2xl font-bold text-text truncate">{task?.name || '-'}</h1>
					{#if task?.is_active !== false}
						<Badge variant="success">{$t.validation?.active || 'Active'}</Badge>
					{:else}
						<Badge variant="muted">{$t.validation?.inactive || 'Inactive'}</Badge>
					{/if}
					{#if isScheduled}
						<Badge variant="primary">{$t.validation?.scheduled || 'Scheduled'}</Badge>
					{:else}
						<Badge variant="muted">{$t.validation?.manual_only || 'Manual only'}</Badge>
					{/if}
				</div>
				<div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-text-muted">
					{#if task?.environment_id}
						<span>
							{$t.validation?.environment || 'Environment'}: {task.environment_id}
						</span>
					{/if}
					{#if task?.provider_id}
						<span>
							{$t.validation?.provider || 'LLM'}: {task.provider_id}
						</span>
					{/if}
					{#if task?.created_at}
						<span>
							{$t.validation?.created_at || 'Created'}: {new Date(task.created_at).toLocaleString()}
						</span>
					{/if}
					{#if task?.updated_at}
						<span>
							{$t.validation?.updated_at || 'Updated'}: {new Date(task.updated_at).toLocaleString()}
						</span>
					{/if}
				</div>
				{#if task?.dashboard_ids?.length}
					<p class="text-sm text-text-muted mt-1">
						{$t.validation?.dashboard || 'Dashboard'}s: {task.dashboard_ids.length}
					</p>
				{/if}
			</div>
			<div class="flex items-center gap-2 ml-4 flex-shrink-0">
				<button
					onclick={handleRunNow}
					disabled={isRunning}
					class="inline-flex items-center px-4 py-2 bg-success text-white rounded-lg hover:bg-success disabled:opacity-50 transition-colors text-sm"
				>
					{#if isRunning}
						<svg class="animate-spin h-4 w-4 mr-2" viewBox="0 0 24 24">
							<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none" />
							<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
						</svg>
						{$t.validation?.running || 'Running...'}
					{:else}
						{$t.validation?.run_now || 'Run Now'}
					{/if}
				</button>
				<button
					onclick={handleEdit}
					class="inline-flex items-center px-4 py-2 border border-border-strong text-text rounded-lg hover:bg-surface-muted transition-colors text-sm"
				>
				<Icon name="edit" size={16} class="mr-1.5" />
					{$t.validation?.edit_task || 'Edit'}
				</button>
				{#if showDeleteConfirm}
					<div class="flex items-center gap-1">
						<button
							onclick={handleDelete}
							class="px-3 py-2 text-sm bg-destructive text-white rounded-lg hover:bg-destructive transition-colors"
						>
							{$t.validation?.confirm_delete || 'Delete'}
						</button>
						<button
							onclick={() => (showDeleteConfirm = false)}
							class="px-3 py-2 text-sm border border-border-strong text-text rounded-lg hover:bg-surface-muted transition-colors"
						>
							{$t.validation?.cancel_delete || 'Cancel'}
						</button>
					</div>
				{:else}
					<button
						onclick={() => (showDeleteConfirm = true)}
						class="inline-flex items-center px-4 py-2 border border-destructive-ring text-destructive rounded-lg hover:bg-destructive-light transition-colors text-sm"
					>
					<Icon name="trash" size={16} class="mr-1.5" />
						{$t.validation?.delete_task_confirm?.split('"')[0]?.trim() || 'Delete'}
					</button>
				{/if}
			</div>
		</div>
	</div>

	<!-- Run History Section -->
	<div class="flex items-center justify-between mb-4">
		<h2 class="text-lg font-semibold text-text">{$t.validation?.run_history || 'Run History'}</h2>
		{#if uxState === 'populated' || uxState === 'empty'}
			<button
				onclick={loadRunHistory}
				class="inline-flex items-center px-3 py-1.5 text-sm border border-border rounded-lg hover:bg-surface-muted transition-colors"
			>
				<Icon name="refresh" size={16} class="mr-1" />
				{$t.common?.refresh || 'Refresh'}
			</button>
		{/if}
	</div>

	<!-- Loading State -->
	{#if uxState === 'loading'}
		<div class="space-y-3">
			{#each Array(4) as _, i (i)}
				<div class="h-14 bg-surface-muted rounded-lg animate-pulse"></div>
			{/each}
		</div>

	<!-- Error State -->
	{:else if uxState === 'error'}
		<div class="bg-destructive-light border border-destructive-ring rounded-lg p-6 text-center">
			<p class="text-destructive mb-3">{errorMsg}</p>
			<button
				onclick={loadRunHistory}
				class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-hover transition-colors"
			>
				{$t.validation?.retry || 'Retry'}
			</button>
		</div>

	<!-- Empty State -->
	{:else if uxState === 'empty'}
		<EmptyState
			title={$t.validation?.run_history_empty || 'No runs for this task yet.'}
			description={$t.validation?.run_history_empty_hint || 'Click "Run Now" above to start a validation run.'}
		/>

	<!-- Populated State -->
	{:else if uxState === 'populated'}
		<div class="bg-surface-card border border-border rounded-lg overflow-hidden">
			<table class="min-w-full divide-y divide-border">
				<thead class="bg-surface-muted">
					<tr>
						<th class="px-4 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">{$t.validation?.timestamp || 'Date/Time'}</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">{$t.validation?.trigger_manual?.split(' ')[0] || 'Trigger'}</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">{$t.validation?.status || 'Status'}</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">{$t.validation?.summary || 'Aggregate'}</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">{$t.validation?.duration || 'Duration'}</th>
						<th class="px-4 py-3 text-right text-xs font-medium text-text-muted uppercase tracking-wider">{$t.validation?.actions || 'Actions'}</th>
					</tr>
				</thead>
				<tbody class="bg-surface-card divide-y divide-border">
					{#each runs as run (run.id)}
						<tr
							onclick={() => handleViewRun(run.id)}
							onkeydown={(e) => { if (e.key === 'Enter') handleViewRun(run.id); }}
							role="button"
							tabindex="0"
							class="hover:bg-surface-muted cursor-pointer transition-colors"
						>
							<td class="px-4 py-3 whitespace-nowrap text-sm text-text-muted">
								{run.timestamp || run.started_at || run.created_at
									? new Date(run.timestamp || run.started_at || run.created_at).toLocaleString()
									: '-'}
							</td>
							<td class="px-4 py-3 whitespace-nowrap text-sm text-text-muted">
								{getTriggerLabel(run.trigger)}
							</td>
							<td class="px-4 py-3 whitespace-nowrap">
								<Badge variant={({ PASS: "success", WARN: "warning", FAIL: "destructive", UNKNOWN: "muted", RUNNING: "primary", PENDING: "warning", COMPLETED: "success" })[run.status] || "muted"}>{run.status || 'UNKNOWN'}</Badge>
							</td>
							<td class="px-4 py-3 whitespace-nowrap text-sm text-text-muted">
								{getAggregateSummary(run)}
							</td>
							<td class="px-4 py-3 whitespace-nowrap text-sm text-text-muted">
								{formatDuration(run.duration_ms)}
							</td>
							<td class="px-4 py-3 whitespace-nowrap text-right">
								<button
									onclick={(e) => { e.stopPropagation(); handleViewRun(run.id); }}
									class="text-primary hover:text-primary text-sm font-medium"
								>
									{$t.validation?.view_report || 'View Report'}
								</button>
							</td>
						</tr>
					{/each}
				</tbody>
			</table>
		</div>

		<!-- Pagination -->
		<Pagination
			bind:page={page0}
			pageSize={pageSize}
			total={total}
			pageSizeOptions={[10, 20, 50, 100]}
			onPageSizeChange={(size) => { pageSize = size; page0 = 0; currentPage = 1; loadRunHistory(); }}
			class="mt-4"
		/>
	{/if}
</div>
<!-- #endregion ValidationTaskDetailPage -->
