<script lang="ts">
	import { post } from '$lib/api/client';
	import ImmichPicker from './ImmichPicker.svelte';

	let {
		entityType,
		entityId,
		images = [],
		documents = [],
		entityName = '',
		tripStart = '',
		tripEnd = '',
		onUpload
	}: {
		entityType: string;
		entityId: string;
		images: any[];
		documents?: any[];
		entityName?: string;
		tripStart?: string;
		tripEnd?: string;
		onUpload: () => void;
	} = $props();

	let uploading = $state(false);
	let deletingId = $state('');
	let showImmich = $state(false);
	let uploadingDoc = $state(false);
	let deletingDocId = $state('');

	// Google image search
	let showSearch = $state(false);
	let searchQuery = $state('');
	let searchResults = $state<Array<{ url: string; thumbnail: string; title: string }>>([]);
	let searching = $state(false);
	let savingUrl = $state('');

	async function handleFileSelect(e: Event) {
		const input = e.target as HTMLInputElement;
		if (!input.files?.length || !entityId) return;

		uploading = true;
		try {
			for (const file of input.files) {
				const reader = new FileReader();
				const base64 = await new Promise<string>((resolve) => {
					reader.onload = () => resolve(reader.result as string);
					reader.readAsDataURL(file);
				});

				await post('/api/image/upload', {
					entity_type: entityType,
					entity_id: entityId,
					image_data: base64,
					filename: file.name
				});
			}
			onUpload();
		} catch (e) {
			console.error('Upload failed:', e);
		} finally {
			uploading = false;
			input.value = '';
		}
	}

	async function deleteImage(imageId: string) {
		deletingId = imageId;
		try {
			await post('/api/image/delete', { id: imageId });
			onUpload();
		} catch (e) {
			console.error('Delete failed:', e);
		} finally {
			deletingId = '';
		}
	}

	async function searchImages() {
		if (!searchQuery.trim()) return;
		searching = true;
		try {
			const data = await post<{ images: typeof searchResults }>('/api/image/search', { query: searchQuery });
			searchResults = data.images || [];
		} catch {
			searchResults = [];
		} finally {
			searching = false;
		}
	}

	async function saveFromUrl(url: string) {
		savingUrl = url;
		try {
			await post('/api/image/upload-from-url', {
				entity_type: entityType,
				entity_id: entityId,
				url
			});
			onUpload();
			showSearch = false;
			searchResults = [];
		} catch (e) {
			console.error('Save from URL failed:', e);
		} finally {
			savingUrl = '';
		}
	}

	function openSearch() {
		searchQuery = entityName || '';
		showSearch = true;
		if (searchQuery) searchImages();
	}

	async function handleDocSelect(e: Event) {
		const input = e.target as HTMLInputElement;
		if (!input.files?.length || !entityId) return;
		uploadingDoc = true;
		try {
			for (const file of input.files) {
				const formData = new FormData();
				formData.append('entity_type', entityType);
				formData.append('entity_id', entityId);
				formData.append('file', file);
				const token = localStorage.getItem('api_token') || '';
				await fetch('/api/document/upload', {
					method: 'POST',
					headers: { 'Authorization': `Bearer ${token}` },
					body: formData
				});
			}
			onUpload();
		} catch (e) { console.error('Doc upload failed:', e); }
		finally { uploadingDoc = false; input.value = ''; }
	}

	async function deleteDoc(docId: string) {
		deletingDocId = docId;
		try {
			await post('/api/document/delete', { document_id: docId });
			onUpload();
		} catch (e) { console.error('Doc delete failed:', e); }
		finally { deletingDocId = ''; }
	}
</script>

<div class="space-y-3">
	<!-- Existing images -->
	{#if images.length > 0}
		<div class="flex gap-2 overflow-x-auto pb-2">
			{#each images as img}
				<div class="relative shrink-0 group">
					<img src={img.url} alt="" class="h-24 w-32 object-cover rounded-lg" />
					<button
						type="button"
						class="absolute top-1 right-1 btn btn-circle btn-xs bg-error/80 border-0 text-white opacity-0 group-hover:opacity-100 transition-opacity"
						onclick={() => deleteImage(img.id)}
						disabled={deletingId === img.id}
					>
						{#if deletingId === img.id}
							<span class="loading loading-spinner loading-xs"></span>
						{:else}
							&#x2715;
						{/if}
					</button>
				</div>
			{/each}
		</div>
	{/if}

	<!-- Existing documents -->
	{#if documents.length > 0}
		<div class="space-y-1">
			{#each documents as doc}
				<div class="flex items-center gap-2 p-1.5 rounded-lg bg-base-300/30 group">
					<svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5 text-base-content/40 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/>
					</svg>
					<a href={doc.url} target="_blank" class="flex-1 text-xs text-base-content/60 hover:text-primary truncate">
						{doc.file_name || doc.original_name || 'Document'}
					</a>
					<button type="button" class="btn btn-ghost btn-xs opacity-0 group-hover:opacity-100 text-error" onclick={() => deleteDoc(doc.id)} disabled={deletingDocId === doc.id}>
						{#if deletingDocId === doc.id}<span class="loading loading-spinner loading-xs"></span>{:else}&#x2715;{/if}
					</button>
				</div>
			{/each}
		</div>
	{/if}

	<!-- Action buttons -->
	{#if entityId}
		<div class="flex flex-wrap gap-2 justify-center">
			<label class="btn btn-ghost btn-sm gap-2 cursor-pointer">
				{#if uploading}
					<span class="loading loading-spinner loading-xs"></span>
					Uploading...
				{:else}
					<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>
					</svg>
					Upload
				{/if}
				<input type="file" accept="image/*" multiple class="hidden" onchange={handleFileSelect} disabled={uploading} />
			</label>

			<button type="button" class="btn btn-ghost btn-sm gap-2" onclick={openSearch}>
				<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
					<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
				</svg>
				Search Web
			</button>

			<button type="button" class="btn btn-ghost btn-sm gap-2" onclick={() => showImmich = true}>
				<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
					<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>
				</svg>
				Immich
			</button>

			<label class="btn btn-ghost btn-sm gap-2 cursor-pointer">
				{#if uploadingDoc}
					<span class="loading loading-spinner loading-xs"></span>
				{:else}
					<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/>
					</svg>
					Document
				{/if}
				<input type="file" accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png,.webp" multiple class="hidden" onchange={handleDocSelect} disabled={uploadingDoc} />
			</label>
		</div>
	{:else}
		<p class="text-xs text-base-content/30">Save first to add photos</p>
	{/if}

	<!-- Google Image Search Panel -->
	{#if showSearch}
		<div class="border border-base-300 rounded-lg p-3 bg-base-300/30">
			<div class="flex gap-2 mb-3">
				<input
					type="text"
					class="input input-bordered input-sm flex-1"
					placeholder="Search for images..."
					bind:value={searchQuery}
					onkeydown={(e) => { if (e.key === 'Enter') { e.preventDefault(); searchImages(); } }}
				/>
				<button type="button" class="btn btn-sm btn-primary" onclick={searchImages} disabled={searching}>
					{#if searching}
						<span class="loading loading-spinner loading-xs"></span>
					{:else}
						Search
					{/if}
				</button>
				<button type="button" class="btn btn-sm btn-ghost" onclick={() => { showSearch = false; searchResults = []; }}>
					&#x2715;
				</button>
			</div>

			{#if searchResults.length > 0}
				<div class="grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-48 overflow-y-auto">
					{#each searchResults as result}
						<button
							type="button"
							class="relative group aspect-square rounded-lg overflow-hidden bg-base-300 hover:ring-2 hover:ring-primary transition-all"
							onclick={() => saveFromUrl(result.url)}
							disabled={savingUrl === result.url}
						>
							<img src={result.thumbnail} alt={result.title} class="w-full h-full object-cover" />
							{#if savingUrl === result.url}
								<div class="absolute inset-0 bg-black/50 flex items-center justify-center">
									<span class="loading loading-spinner loading-sm text-white"></span>
								</div>
							{:else}
								<div class="absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center">
									<span class="text-white opacity-0 group-hover:opacity-100 text-xs font-medium">Save</span>
								</div>
							{/if}
						</button>
					{/each}
				</div>
			{:else if !searching && searchQuery}
				<p class="text-sm text-base-content/40 text-center py-4">No results</p>
			{/if}
		</div>
	{/if}

	<!-- Immich Picker -->
	{#if showImmich && entityId}
		<ImmichPicker {entityType} {entityId} {tripStart} {tripEnd} onImport={() => { showImmich = false; onUpload(); }} onClose={() => showImmich = false} />
	{/if}
</div>
