<script lang="ts">
	import type { Project, EntityPickerItem } from '$lib/types';
	import * as api from '$lib/api';
	import { t } from '$lib/i18n';
	import { IconPlus, IconSearch, IconLoader } from '$lib/components/icons';
	import FormField from '$lib/components/FormField.svelte';
	import SkeletonTable from '$lib/components/SkeletonTable.svelte';
	import EmptyState from '$lib/components/EmptyState.svelte';
	import EntityPicker from '$lib/components/EntityPicker.svelte';

	let projects = $state<Project[]>([]);
	let loading = $state(true);
	let error = $state('');
	let showAddForm = $state(false);
	let searchQuery = $state('');

	const filteredProjects = $derived(
		searchQuery.trim()
			? projects.filter(p => {
				const q = searchQuery.toLowerCase();
				return p.name.toLowerCase().includes(q)
					|| p.image.toLowerCase().includes(q)
					|| (p.registry ?? '').toLowerCase().includes(q);
			})
			: projects
	);

	let formName = $state('');
	let formImage = $state('');
	let formRegistry = $state('');
	let formPort = $state('3000');
	let formHealthcheck = $state('');
	let formSubmitting = $state(false);
	let formError = $state('');

	// Image picker state
	let showImagePicker = $state(false);
	let imagePickerItems = $state<EntityPickerItem[]>([]);
	let imagePickerLoading = $state(false);

	async function handleBrowseImages() {
		showImagePicker = true;
		if (imagePickerItems.length > 0) return;

		imagePickerLoading = true;
		try {
			const registries = await api.listRegistries();
			// Collect existing project images to mark as already added.
			const existingImages = new Set(projects.map(p => p.image.toLowerCase()));
			const items: EntityPickerItem[] = [];
			for (const reg of registries) {
				if (!reg.owner) continue;
				try {
					const images = await api.listRegistryImages(reg.id);
					for (const img of images) {
						const alreadyAdded = existingImages.has(img.full_ref.toLowerCase());
						items.push({
							value: JSON.stringify({ full_ref: img.full_ref, registryName: reg.name }),
							label: img.full_ref,
							description: alreadyAdded ? undefined : reg.name,
							group: reg.name,
							disabled: alreadyAdded,
							disabledHint: alreadyAdded ? $t('projects.alreadyAdded') : undefined
						});
					}
				} catch {
					// Skip registries that fail (e.g., no owner configured).
				}
			}
			imagePickerItems = items;
		} catch {
			imagePickerItems = [];
		} finally {
			imagePickerLoading = false;
		}
	}

	function nameFromImage(imageRef: string): string {
		// Extract last path segment: "git.example.com/owner/my-app" → "my-app"
		const parts = imageRef.split('/');
		return parts[parts.length - 1].toLowerCase().replace(/[^a-z0-9-]/g, '-');
	}

	function selectPickedImage(value: string) {
		const parsed = JSON.parse(value) as { full_ref: string; registryName: string };
		formImage = parsed.full_ref;
		formRegistry = parsed.registryName;
		// Auto-fill name if empty.
		if (!formName.trim()) {
			formName = nameFromImage(parsed.full_ref);
		}
		showImagePicker = false;
	}

	async function loadProjects() {
		loading = true;
		error = '';
		try {
			projects = await api.listProjects();
		} catch (e) {
			error = e instanceof Error ? e.message : $t('projects.loadFailed');
		} finally {
			loading = false;
		}
	}

	async function handleAddProject() {
		if (!formName.trim() || !formImage.trim()) {
			formError = $t('projects.nameRequired');
			return;
		}

		formSubmitting = true;
		formError = '';
		try {
			await api.createProject({
				name: formName.trim(),
				image: formImage.trim(),
				registry: formRegistry.trim(),
				port: parseInt(formPort, 10) || 3000,
				healthcheck: formHealthcheck.trim()
			});
			formName = '';
			formImage = '';
			formRegistry = '';
			formPort = '3000';
			formHealthcheck = '';
			showAddForm = false;
			await loadProjects();
		} catch (e) {
			formError = e instanceof Error ? e.message : $t('projects.createFailed');
		} finally {
			formSubmitting = false;
		}
	}

	$effect(() => {
		loadProjects();
	});
</script>

<svelte:head>
	<title>{$t('projects.title')} - {$t('app.name')}</title>
</svelte:head>

<div class="space-y-6">
	<div class="flex items-center justify-between">
		<h1 class="text-2xl font-bold text-[var(--text-primary)]">{$t('projects.title')}</h1>
		<button
			type="button"
			class="inline-flex items-center gap-2 rounded-lg {showAddForm ? 'border border-[var(--border-primary)] bg-[var(--surface-card)] text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)]' : 'bg-[var(--color-brand-600)] text-white shadow-sm hover:bg-[var(--color-brand-700)]'} px-4 py-2.5 text-sm font-medium transition-all duration-150 active:animate-press"
			onclick={() => { showAddForm = !showAddForm; }}
		>
			{#if !showAddForm}<IconPlus size={16} />{/if}
			{showAddForm ? $t('projects.cancel') : $t('projects.addProject')}
		</button>
	</div>

	<!-- Add project form -->
	{#if showAddForm}
		<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 animate-scale-in">
			<h2 class="text-lg font-semibold text-[var(--text-primary)]">{$t('projects.newProject')}</h2>

			{#if formError}
				<div class="mt-3 rounded-lg bg-[var(--color-danger-light)] p-3">
					<p class="text-sm text-[var(--color-danger)]">{formError}</p>
				</div>
			{/if}

			<div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
				<FormField label="{$t('projects.name')} *" name="name" bind:value={formName} placeholder="my-web-app" required />
				<div class="flex items-end gap-2">
					<div class="flex-1">
						<FormField label="{$t('projects.image')} *" name="image" bind:value={formImage} placeholder="registry.example.com/org/app" required />
					</div>
					<button
						type="button"
						onclick={handleBrowseImages}
						title={$t('projects.browseImages')}
						aria-label={$t('projects.browseImages')}
						class="rounded-lg border border-[var(--border-primary)] p-2 text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)] hover:text-[var(--text-primary)] transition-colors"
					>
						{#if imagePickerLoading}
							<IconLoader size={16} />
						{:else}
							<IconSearch size={16} />
						{/if}
					</button>
				</div>
				<EntityPicker
					bind:open={showImagePicker}
					items={imagePickerItems}
					current={formImage}
					title={$t('projects.selectImage')}
					placeholder={$t('entityPicker.search')}
					onselect={selectPickedImage}
					onclose={() => { showImagePicker = false; }}
				/>
				<FormField label={$t('projects.port')} name="port" type="number" bind:value={formPort} helpText={$t('projects.portHelpText')} />
				<FormField label={$t('projects.healthcheck')} name="healthcheck" bind:value={formHealthcheck} placeholder="/api/health" helpText={$t('projects.healthcheckHelpText')} />
			</div>

			<div class="mt-6 flex justify-end">
				<button
					type="button"
					class="rounded-lg bg-[var(--color-brand-600)] px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-[var(--color-brand-700)] disabled:opacity-50 transition-all duration-150 active:animate-press"
					disabled={formSubmitting}
					onclick={handleAddProject}
				>
					{formSubmitting ? $t('projects.creating') : $t('projects.createProject')}
				</button>
			</div>
		</div>
	{/if}

	<!-- Projects list -->
	{#if loading}
		<SkeletonTable rows={4} cols={5} />
	{:else if error}
		<div class="rounded-xl border border-[var(--color-danger-light)] bg-[var(--color-danger-light)] p-4">
			<p class="text-sm text-[var(--color-danger)]">{error}</p>
			<button type="button" class="mt-2 text-sm font-medium text-[var(--color-danger)] underline hover:no-underline" onclick={loadProjects}>
				{$t('common.retry')}
			</button>
		</div>
	{:else if projects.length === 0}
		<EmptyState
			title={$t('empty.noProjects')}
			description={$t('empty.noProjectsDesc')}
			actionLabel={$t('projects.addProject')}
			onaction={() => { showAddForm = true; }}
			icon="projects"
		/>
	{:else}
		<!-- Search filter -->
		<div class="relative">
			<IconSearch size={16} class="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text-tertiary)]" />
			<input
				type="text"
				bind:value={searchQuery}
				placeholder={$t('projects.searchPlaceholder')}
				class="w-full rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card)] py-2.5 pl-10 pr-4 text-sm text-[var(--text-primary)] placeholder:text-[var(--text-tertiary)] focus:border-[var(--color-brand-500)] focus:outline-none focus:ring-1 focus:ring-[var(--color-brand-500)]"
			/>
		</div>

		{#if filteredProjects.length === 0}
			<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-8 text-center">
				<p class="text-sm text-[var(--text-tertiary)]">{$t('projects.noMatchingProjects')}</p>
			</div>
		{:else}
		<div class="overflow-x-auto rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] shadow-[var(--shadow-sm)]">
			<table class="min-w-full divide-y divide-[var(--border-primary)]">
				<thead class="bg-[var(--surface-card-hover)]">
					<tr>
						<th class="px-6 py-3 text-left text-xs font-medium tracking-wider text-[var(--text-tertiary)] uppercase">{$t('projects.name')}</th>
						<th class="px-6 py-3 text-left text-xs font-medium tracking-wider text-[var(--text-tertiary)] uppercase">{$t('projects.image')}</th>
						<th class="px-6 py-3 text-left text-xs font-medium tracking-wider text-[var(--text-tertiary)] uppercase">{$t('projects.port')}</th>
						<th class="px-6 py-3 text-left text-xs font-medium tracking-wider text-[var(--text-tertiary)] uppercase">{$t('projects.registry')}</th>
						<th class="px-6 py-3 text-left text-xs font-medium tracking-wider text-[var(--text-tertiary)] uppercase">{$t('projects.created')}</th>
						<th class="px-6 py-3"></th>
					</tr>
				</thead>
				<tbody class="divide-y divide-[var(--border-secondary)]">
					{#each filteredProjects as project (project.id)}
						<tr class="hover:bg-[var(--surface-card-hover)] transition-colors duration-150">
							<td class="whitespace-nowrap px-6 py-4">
								<a href="/projects/{project.id}" class="font-medium text-[var(--text-link)] hover:text-[var(--text-link-hover)] transition-colors">
									{project.name}
								</a>
							</td>
							<td class="max-w-xs truncate px-6 py-4 font-mono text-sm text-[var(--text-tertiary)]">
								{project.image}
							</td>
							<td class="whitespace-nowrap px-6 py-4 text-sm text-[var(--text-secondary)]">
								{project.port || '-'}
							</td>
							<td class="whitespace-nowrap px-6 py-4 text-sm text-[var(--text-secondary)]">
								{project.registry || '-'}
							</td>
							<td class="whitespace-nowrap px-6 py-4 text-sm text-[var(--text-secondary)]">
								{new Date(project.created_at).toLocaleDateString()}
							</td>
							<td class="whitespace-nowrap px-6 py-4 text-right text-sm">
								<a href="/projects/{project.id}" class="text-[var(--text-link)] hover:text-[var(--text-link-hover)] transition-colors">
									{$t('projects.view')}
								</a>
							</td>
						</tr>
					{/each}
				</tbody>
			</table>
		</div>
		{/if}
	{/if}
</div>
