<script lang="ts">
import { onDestroy } from 'svelte';
import { m } from '$lib/paraglide/messages.js';
import ImportStatusCard from './ImportStatusCard.svelte';
import type { ImportStatus } from './types.js';

let backfillResult: number | null = $state(null);
let backfillLoading = $state(false);
let backfillHashesResult: number | null = $state(null);
let backfillHashesLoading = $state(false);

type ThumbnailStatus = {
	state: 'IDLE' | 'RUNNING' | 'DONE' | 'FAILED';
	message: string;
	total: number;
	processed: number;
	skipped: number;
	failed: number;
	startedAt: string | null;
};

let importStatus: ImportStatus | null = $state(null);
let thumbnailStatus: ThumbnailStatus | null = $state(null);
let pollInterval: ReturnType<typeof setInterval> | null = null;
let thumbnailPollInterval: ReturnType<typeof setInterval> | null = null;

function startPolling() {
	if (pollInterval) return;
	pollInterval = setInterval(fetchImportStatus, 2000);
}

function stopPolling() {
	if (pollInterval) {
		clearInterval(pollInterval);
		pollInterval = null;
	}
}

function startThumbnailPolling() {
	if (thumbnailPollInterval) return;
	thumbnailPollInterval = setInterval(fetchThumbnailStatus, 2000);
}

function stopThumbnailPolling() {
	if (thumbnailPollInterval) {
		clearInterval(thumbnailPollInterval);
		thumbnailPollInterval = null;
	}
}

async function fetchImportStatus() {
	const res = await fetch('/api/admin/import-status');
	if (res.ok) {
		importStatus = await res.json();
		if (importStatus!.state === 'RUNNING') {
			startPolling();
		} else {
			stopPolling();
		}
	}
}

async function triggerImport() {
	const res = await fetch('/api/admin/trigger-import', { method: 'POST' });
	if (res.ok) {
		importStatus = await res.json();
		if (importStatus!.state === 'RUNNING') {
			startPolling();
		}
	}
}

async function fetchThumbnailStatus() {
	const res = await fetch('/api/admin/thumbnail-status');
	if (res.ok) {
		thumbnailStatus = await res.json();
		if (thumbnailStatus!.state === 'RUNNING') {
			startThumbnailPolling();
		} else {
			stopThumbnailPolling();
		}
	}
}

async function triggerThumbnails() {
	const res = await fetch('/api/admin/generate-thumbnails', { method: 'POST' });
	if (res.ok) {
		thumbnailStatus = await res.json();
		if (thumbnailStatus!.state === 'RUNNING') {
			startThumbnailPolling();
		}
	}
}

$effect(() => {
	fetchImportStatus();
	fetchThumbnailStatus();
});

onDestroy(() => {
	stopPolling();
	stopThumbnailPolling();
});

async function backfillVersions() {
	backfillLoading = true;
	backfillResult = null;
	try {
		const res = await fetch('/api/admin/backfill-versions', { method: 'POST' });
		if (res.ok) {
			const data = await res.json();
			backfillResult = data.count;
		}
	} finally {
		backfillLoading = false;
	}
}

async function backfillFileHashes() {
	backfillHashesLoading = true;
	backfillHashesResult = null;
	try {
		const res = await fetch('/api/admin/backfill-file-hashes', { method: 'POST' });
		if (res.ok) {
			const data = await res.json();
			backfillHashesResult = data.count;
		}
	} finally {
		backfillHashesLoading = false;
	}
}
</script>

<div class="flex-1 overflow-y-auto p-6">
	<div class="mx-auto max-w-2xl space-y-5">
		<!-- Backfill versions -->
		<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
			<h2 class="mb-1 font-sans text-sm font-bold text-ink">{m.admin_system_backfill_heading()}</h2>
			<p class="mb-4 text-sm text-ink-2">{m.admin_system_backfill_description()}</p>
			<button
				onclick={backfillVersions}
				disabled={backfillLoading}
				class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-50"
			>
				{backfillLoading ? '…' : m.admin_system_backfill_btn()}
			</button>
			{#if backfillResult !== null}
				<p class="mt-4 rounded-sm border border-green-200 bg-green-50 p-3 text-sm text-green-700">
					{m.admin_system_backfill_success({ count: backfillResult })}
				</p>
			{/if}
		</div>

		<!-- Backfill file hashes -->
		<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
			<h2 class="mb-1 font-sans text-sm font-bold text-ink">
				{m.admin_system_backfill_hashes_heading()}
			</h2>
			<p class="mb-4 text-sm text-ink-2">{m.admin_system_backfill_hashes_description()}</p>
			<button
				onclick={backfillFileHashes}
				disabled={backfillHashesLoading}
				class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-50"
			>
				{backfillHashesLoading ? '…' : m.admin_system_backfill_hashes_btn()}
			</button>
			{#if backfillHashesResult !== null}
				<p class="mt-4 rounded-sm border border-green-200 bg-green-50 p-3 text-sm text-green-700">
					{m.admin_system_backfill_hashes_success({ count: backfillHashesResult })}
				</p>
			{/if}
		</div>

		<!-- Mass import -->
		<ImportStatusCard importStatus={importStatus} ontrigger={triggerImport} />

		<!-- Thumbnail backfill -->
		<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
			<h2 class="mb-1 font-sans text-sm font-bold text-ink">
				{m.admin_system_thumbnails_heading()}
			</h2>
			<p class="mb-4 text-sm text-ink-2">{m.admin_system_thumbnails_description()}</p>

			{#if thumbnailStatus?.state === 'RUNNING'}
				<p class="text-sm text-ink-2">
					{m.admin_system_thumbnails_status_running()}
					{#if thumbnailStatus.total > 0}
						<span class="text-ink-3">
							({thumbnailStatus.processed + thumbnailStatus.skipped + thumbnailStatus.failed} /
							{thumbnailStatus.total})
						</span>
					{/if}
				</p>
			{:else if thumbnailStatus?.state === 'DONE'}
				<p
					data-testid="thumbnails-status-done"
					class="mb-4 rounded-sm border border-green-200 bg-green-50 p-3 text-sm text-green-700"
				>
					{m.admin_system_thumbnails_status_done({
						processed: thumbnailStatus.processed,
						skipped: thumbnailStatus.skipped,
						failed: thumbnailStatus.failed
					})}
				</p>
				<button
					data-thumbnails-trigger
					onclick={triggerThumbnails}
					class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
				>
					{m.admin_system_thumbnails_btn_retry()}
				</button>
			{:else if thumbnailStatus?.state === 'FAILED'}
				<p class="mb-4 rounded-sm border border-red-200 bg-red-50 p-3 text-sm text-red-700">
					{m.admin_system_thumbnails_status_failed({ message: thumbnailStatus.message })}
				</p>
				<button
					data-thumbnails-trigger
					onclick={triggerThumbnails}
					class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
				>
					{m.admin_system_thumbnails_btn_retry()}
				</button>
			{:else}
				<button
					data-thumbnails-trigger
					onclick={triggerThumbnails}
					class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
				>
					{m.admin_system_thumbnails_btn_start()}
				</button>
			{/if}
		</div>
	</div>
</div>
