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

	let {
		entityType,
		entityId,
		documents = [],
		onUpload
	}: {
		entityType: string;
		entityId: string;
		documents: any[];
		onUpload: () => void;
	} = $props();

	let uploading = $state(false);
	let deletingId = $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 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('Upload failed:', e);
		} finally {
			uploading = false;
			input.value = '';
		}
	}

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

	function fileIcon(mime: string): string {
		if (mime?.includes('pdf')) return 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6';
		if (mime?.includes('image')) return 'M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM8.5 8.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM21 15l-5-5L5 21';
		return 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6';
	}
</script>

<div class="space-y-2">
	<!-- Existing documents -->
	{#if documents.length > 0}
		<div class="space-y-1">
			{#each documents as doc}
				<div class="flex items-center gap-2 p-2 rounded-lg bg-base-300/30 group">
					<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 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={fileIcon(doc.mime_type)}/>
					</svg>
					<a href={doc.url} target="_blank" class="flex-1 text-sm text-base-content/70 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={deletingId === doc.id}
					>
						{#if deletingId === doc.id}
							<span class="loading loading-spinner loading-xs"></span>
						{:else}
							&#x2715;
						{/if}
					</button>
				</div>
			{/each}
		</div>
	{/if}

	<!-- Upload button -->
	{#if entityId}
		<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">
					<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"/><line x1="12" y1="18" x2="12" y2="12"/><line x1="9" y1="15" x2="15" y2="15"/>
				</svg>
				Add Document
			{/if}
			<input type="file" accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png,.webp" multiple class="hidden" onchange={handleFileSelect} disabled={uploading} />
		</label>
	{:else}
		<p class="text-xs text-base-content/30">Save first to add documents</p>
	{/if}
</div>
