<script lang="ts">
	import type { PageData } from './$types';
	import type { Repository, RepositoryVersion, IndexingJob } from '$lib/types';
	import ConfirmDialog from '$lib/components/ConfirmDialog.svelte';
	import IndexingProgress from '$lib/components/IndexingProgress.svelte';
	import StatBadge from '$lib/components/StatBadge.svelte';

	let { data }: { data: PageData } = $props();

	// Initialized empty; $effect syncs from data prop on every navigation/reload.
	let repo = $state<Repository & { versions?: RepositoryVersion[] }>({} as Repository & { versions?: RepositoryVersion[] });
	let recentJobs = $state<IndexingJob[]>([]);
	$effect(() => {
		if (data.repo) repo = data.repo;
		recentJobs = data.recentJobs ?? [];
	});
	let showDeleteConfirm = $state(false);
	let activeJobId = $state<string | null>(null);
	let errorMessage = $state<string | null>(null);
	let successMessage = $state<string | null>(null);

	const stateColors: Record<string, string> = {
		pending: 'bg-gray-100 text-gray-600',
		indexing: 'bg-blue-100 text-blue-700',
		indexed: 'bg-green-100 text-green-700',
		error: 'bg-red-100 text-red-700'
	};

	const stateLabels: Record<string, string> = {
		pending: 'Pending',
		indexing: 'Indexing...',
		indexed: 'Indexed',
		error: 'Error'
	};

	async function refreshRepo() {
		try {
			const res = await fetch(`/api/v1/libs/${encodeURIComponent(repo.id)}`);
			if (res.ok) {
				repo = await res.json();
			}
		} catch {
			// ignore
		}
	}

	async function handleReindex() {
		errorMessage = null;
		successMessage = null;
		try {
			const res = await fetch(`/api/v1/libs/${encodeURIComponent(repo.id)}/index`, {
				method: 'POST'
			});
			if (!res.ok) {
				const d = await res.json();
				throw new Error(d.error ?? 'Failed to trigger re-indexing');
			}
			const d = await res.json();
			if (d.job?.id) {
				activeJobId = d.job.id;
			}
			successMessage = 'Re-indexing started.';
			await refreshRepo();
		} catch (e) {
			errorMessage = (e as Error).message;
		}
	}

	async function handleDelete() {
		showDeleteConfirm = false;
		errorMessage = null;
		try {
			const res = await fetch(`/api/v1/libs/${encodeURIComponent(repo.id)}`, {
				method: 'DELETE'
			});
			if (!res.ok && res.status !== 204) {
				const d = await res.json();
				throw new Error(d.error ?? 'Failed to delete repository');
			}
			window.location.href = '/';
		} catch (e) {
			errorMessage = (e as Error).message;
		}
	}

	function formatDate(ts: Date | number | string | null | undefined): string {
		if (!ts) return 'Never';
		return new Date(ts as string).toLocaleString();
	}

	const versions = $derived(repo.versions ?? []);
	const totalSnippets = $derived(repo.totalSnippets ?? 0);
	const totalTokens = $derived(repo.totalTokens ?? 0);
	const trustScore = $derived(repo.trustScore ?? 0);
</script>

<svelte:head>
	<title>{repo.title} — TrueRef</title>
</svelte:head>

<div class="mb-6">
	<a href="/" class="text-sm text-blue-600 hover:underline">← Repositories</a>
</div>

<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
	<div class="min-w-0 flex-1">
		<div class="flex flex-wrap items-center gap-3">
			<h1 class="text-xl font-semibold text-gray-900">{repo.title}</h1>
			<span
				class="rounded-full px-2.5 py-0.5 text-xs font-medium {stateColors[repo.state] ??
					'bg-gray-100 text-gray-600'}"
			>
				{stateLabels[repo.state] ?? repo.state}
			</span>
		</div>
		<p class="mt-1 font-mono text-sm text-gray-500">{repo.id}</p>
		{#if repo.description}
			<p class="mt-2 text-sm text-gray-600">{repo.description}</p>
		{/if}
		{#if repo.sourceUrl}
			{#if repo.source === 'github'}
				<a
					href={repo.sourceUrl}
					target="_blank"
					rel="noopener noreferrer"
					class="mt-1 block text-sm text-blue-600 hover:underline"
				>
					{repo.sourceUrl}
				</a>
			{:else}
				<p class="mt-1 font-mono text-sm text-gray-500">{repo.sourceUrl}</p>
			{/if}
		{/if}
	</div>

	<div class="flex shrink-0 gap-2">
		<button
			onclick={handleReindex}
			disabled={repo.state === 'indexing'}
			class="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
		>
			{repo.state === 'indexing' ? 'Indexing...' : 'Re-index'}
		</button>
		<button
			onclick={() => (showDeleteConfirm = true)}
			class="rounded-lg border border-red-200 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50"
		>
			Delete
		</button>
	</div>
</div>

{#if errorMessage}
	<div class="mt-4 rounded-lg bg-red-50 px-4 py-3">
		<p class="text-sm text-red-700">{errorMessage}</p>
	</div>
{/if}

{#if successMessage}
	<div class="mt-4 rounded-lg bg-green-50 px-4 py-3">
		<p class="text-sm text-green-700">{successMessage}</p>
	</div>
{/if}

{#if activeJobId}
	<div class="mt-4 rounded-xl border border-blue-100 bg-blue-50 p-4">
		<p class="mb-2 text-sm font-medium text-blue-700">Indexing in progress</p>
		<IndexingProgress jobId={activeJobId} />
	</div>
{:else if repo.state === 'error'}
	<div class="mt-4 rounded-xl border border-red-100 bg-red-50 p-4">
		<p class="text-sm text-red-700">Last indexing run failed. Trigger re-index to retry.</p>
	</div>
{/if}

<!-- Stats -->
<div class="mt-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
	<StatBadge label="Snippets" value={totalSnippets.toLocaleString()} />
	<StatBadge label="Tokens" value={totalTokens.toLocaleString()} />
	<StatBadge label="Trust Score" value="{trustScore.toFixed(1)}/10" />
	{#if repo.stars != null}
		<StatBadge label="Stars" value={repo.stars.toLocaleString()} />
	{/if}
</div>

<!-- Metadata -->
<div class="mt-6 rounded-xl border border-gray-200 bg-white p-5">
	<h2 class="mb-3 text-sm font-semibold text-gray-700">Repository Info</h2>
	<dl class="grid grid-cols-1 gap-y-2 text-sm sm:grid-cols-2">
		<div class="flex gap-2">
			<dt class="text-gray-500">Source</dt>
			<dd class="font-medium capitalize text-gray-900">{repo.source}</dd>
		</div>
		<div class="flex gap-2">
			<dt class="text-gray-500">Branch</dt>
			<dd class="font-medium text-gray-900">{repo.branch ?? 'main'}</dd>
		</div>
		<div class="flex gap-2">
			<dt class="text-gray-500">Last Indexed</dt>
			<dd class="font-medium text-gray-900">{formatDate(repo.lastIndexedAt)}</dd>
		</div>
		<div class="flex gap-2">
			<dt class="text-gray-500">Created</dt>
			<dd class="font-medium text-gray-900">{formatDate(repo.createdAt)}</dd>
		</div>
	</dl>
</div>

<!-- Versions -->
{#if versions.length > 0}
	<div class="mt-6 rounded-xl border border-gray-200 bg-white p-5">
		<h2 class="mb-3 text-sm font-semibold text-gray-700">Indexed Versions</h2>
		<div class="divide-y divide-gray-100">
			{#each versions as version (version.id)}
				<div class="flex items-center justify-between py-2.5">
					<div>
						<span class="font-mono text-sm font-medium text-gray-900">{version.tag}</span>
						{#if version.title}
							<span class="ml-2 text-sm text-gray-500">{version.title}</span>
						{/if}
					</div>
					<div class="flex items-center gap-3">
						<span
							class="rounded-full px-2 py-0.5 text-xs {stateColors[version.state] ??
								'bg-gray-100 text-gray-600'}"
						>
							{stateLabels[version.state] ?? version.state}
						</span>
						{#if version.indexedAt}
							<span class="text-xs text-gray-400">{formatDate(version.indexedAt)}</span>
						{/if}
					</div>
				</div>
			{/each}
		</div>
	</div>
{/if}

<!-- Recent Jobs -->
{#if recentJobs.length > 0}
	<div class="mt-6 rounded-xl border border-gray-200 bg-white p-5">
		<h2 class="mb-3 text-sm font-semibold text-gray-700">Recent Jobs</h2>
		<div class="divide-y divide-gray-100">
			{#each recentJobs as job (job.id)}
				<div class="flex items-center justify-between py-2.5">
					<div>
						<span class="font-mono text-xs text-gray-500">{job.id.slice(0, 8)}...</span>
						{#if job.error}
							<p class="mt-0.5 text-xs text-red-600">{job.error}</p>
						{/if}
					</div>
					<div class="flex items-center gap-3">
						<span
							class="rounded-full px-2 py-0.5 text-xs {job.status === 'done'
								? 'bg-green-100 text-green-700'
								: job.status === 'failed'
									? 'bg-red-100 text-red-700'
									: job.status === 'running'
										? 'bg-blue-100 text-blue-700'
										: 'bg-gray-100 text-gray-600'}"
						>
							{job.status}
						</span>
						{#if job.completedAt}
							<span class="text-xs text-gray-400">{formatDate(job.completedAt)}</span>
						{:else if job.startedAt}
							<span class="text-xs text-gray-400">{formatDate(job.startedAt)}</span>
						{/if}
					</div>
				</div>
			{/each}
		</div>
	</div>
{/if}

{#if showDeleteConfirm}
	<ConfirmDialog
		title="Delete Repository"
		message="Are you sure you want to delete {repo.title}? This will permanently remove all indexed snippets and job history."
		confirmLabel="Delete"
		danger={true}
		onConfirm={handleDelete}
		onCancel={() => (showDeleteConfirm = false)}
	/>
{/if}
