<script lang="ts">
	import {
		FileText,
		FolderOpen,
		Download,
		Eye,
		Calendar,
		Search,
		Filter,
		Grid,
		List
	} from 'lucide-svelte';
	import { Input } from '$lib/components/ui/input';
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';

	let { data } = $props();
	const { documents, categories } = data;

	let searchQuery = $state(data.searchQuery || '');
	let selectedCategory = $state<string | null>(null);
	let viewMode = $state<'grid' | 'list'>('grid');

	// Debounce server-side search
	let searchTimeout: ReturnType<typeof setTimeout>;
	function handleSearch(value: string) {
		clearTimeout(searchTimeout);
		searchTimeout = setTimeout(() => {
			const params = new URLSearchParams($page.url.searchParams);
			if (value.trim()) {
				params.set('q', value.trim());
			} else {
				params.delete('q');
			}
			goto(`?${params.toString()}`, { replaceState: true, keepFocus: true });
		}, 400);
	}

	// Filter documents (category is still client-side for instant feedback)
	const filteredDocuments = $derived(
		(documents || []).filter((doc: any) => {
			const matchesCategory = !selectedCategory || doc.category_id === selectedCategory;
			return matchesCategory;
		})
	);

	// Format date
	function formatDate(dateStr: string): string {
		return new Date(dateStr).toLocaleDateString('en-US', {
			year: 'numeric',
			month: 'short',
			day: 'numeric'
		});
	}

	// Format file size
	function formatFileSize(bytes: number): string {
		if (bytes < 1024) return bytes + ' B';
		if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
		return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
	}

	// Get file icon based on mime type
	function getFileIcon(mimeType: string) {
		if (mimeType.includes('pdf')) return 'pdf';
		if (mimeType.includes('word') || mimeType.includes('document')) return 'doc';
		if (mimeType.includes('sheet') || mimeType.includes('excel')) return 'xls';
		if (mimeType.includes('presentation') || mimeType.includes('powerpoint')) return 'ppt';
		if (mimeType.includes('image')) return 'img';
		return 'file';
	}

	// Get category by ID
	function getCategory(categoryId: string | null) {
		return categories?.find((c: any) => c.id === categoryId);
	}
</script>

<svelte:head>
	<title>Documents | Monaco USA</title>
</svelte:head>

<div class="space-y-6">
	<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
		<div>
			<h1 class="text-2xl font-bold text-slate-900">Documents</h1>
			<p class="text-slate-500">Meeting minutes, bylaws, and resources</p>
		</div>

		<div class="flex items-center gap-2">
			<div class="flex rounded-lg border border-slate-200 bg-white p-1">
				<button
					onclick={() => (viewMode = 'grid')}
					class="rounded-md p-1.5 {viewMode === 'grid' ? 'bg-monaco-100 text-monaco-700' : 'text-slate-500'}"
				>
					<Grid class="h-4 w-4" />
				</button>
				<button
					onclick={() => (viewMode = 'list')}
					class="rounded-md p-1.5 {viewMode === 'list' ? 'bg-monaco-100 text-monaco-700' : 'text-slate-500'}"
				>
					<List class="h-4 w-4" />
				</button>
			</div>
		</div>
	</div>

	<!-- Filters -->
	<div class="space-y-4">
		<!-- Search bar - always full width -->
		<div class="relative">
			<Search class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
			<Input
				type="search"
				placeholder="Search documents by title, description, or filename..."
				value={searchQuery}
				oninput={(e) => {
					searchQuery = e.currentTarget.value;
					handleSearch(e.currentTarget.value);
				}}
				class="h-10 w-full pl-9"
			/>
		</div>

		<!-- Category filters -->
		<div class="flex flex-wrap gap-2">
			<button
				onclick={() => (selectedCategory = null)}
				class="rounded-full px-3 py-1.5 text-sm font-medium transition-colors {selectedCategory ===
				null
					? 'bg-monaco-100 text-monaco-700'
					: 'bg-slate-100 text-slate-600 hover:bg-slate-200'}"
			>
				All
			</button>
			{#each categories || [] as category}
				<button
					onclick={() => (selectedCategory = category.id)}
					class="rounded-full px-3 py-1.5 text-sm font-medium transition-colors {selectedCategory ===
					category.id
						? 'bg-monaco-100 text-monaco-700'
						: 'bg-slate-100 text-slate-600 hover:bg-slate-200'}"
				>
					{category.display_name}
				</button>
			{/each}
		</div>
	</div>

	<!-- Documents -->
	{#if filteredDocuments.length === 0}
		<div class="glass-card flex flex-col items-center justify-center p-12 text-center">
			<FolderOpen class="mb-4 h-16 w-16 text-slate-300" />
			<h3 class="text-lg font-medium text-slate-900">No documents found</h3>
			<p class="mt-1 text-slate-500">
				{searchQuery || selectedCategory
					? 'Try adjusting your search or filters.'
					: 'Documents will appear here when added.'}
			</p>
		</div>
	{:else if viewMode === 'grid'}
		<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
			{#each filteredDocuments as doc}
				{@const category = getCategory(doc.category_id)}
				<div class="glass-card overflow-hidden transition-all hover:shadow-md">
					<div class="border-b border-slate-100 bg-slate-50 px-4 py-3">
						<div class="flex items-center gap-2">
							<FileText class="h-5 w-5 text-monaco-600" />
							<span class="text-xs font-medium uppercase text-slate-500">
								{getFileIcon(doc.mime_type)}
							</span>
							{#if category}
								<span class="rounded-full bg-slate-200 px-2 py-0.5 text-xs text-slate-600">
									{category.display_name}
								</span>
							{/if}
						</div>
					</div>

					<div class="p-4">
						<h3 class="font-medium text-slate-900">{doc.title}</h3>
						{#if doc.description}
							<p class="mt-1 line-clamp-2 text-sm text-slate-500">{doc.description}</p>
						{/if}

						<div class="mt-3 flex items-center gap-4 text-xs text-slate-500">
							<span class="flex items-center gap-1">
								<Calendar class="h-3.5 w-3.5" />
								{formatDate(doc.created_at)}
							</span>
							<span>{formatFileSize(doc.file_size)}</span>
						</div>

						<div class="mt-4 flex gap-2">
							<a
								href={doc.active_url}
								target="_blank"
								rel="noopener noreferrer"
								class="inline-flex flex-1 items-center justify-center gap-1.5 rounded-lg bg-slate-100 px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-200"
							>
								<Eye class="h-4 w-4" />
								View
							</a>
							<a
								href={doc.active_url}
								download={doc.file_name}
								class="inline-flex flex-1 items-center justify-center gap-1.5 rounded-lg bg-monaco-100 px-3 py-2 text-sm font-medium text-monaco-700 hover:bg-monaco-200"
							>
								<Download class="h-4 w-4" />
								Download
							</a>
						</div>
					</div>
				</div>
			{/each}
		</div>
	{:else}
		<!-- List View -->
		<div class="glass-card overflow-hidden">
			<table class="w-full">
				<thead class="bg-slate-50">
					<tr>
						<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">
							Document
						</th>
						<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">
							Category
						</th>
						<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">
							Date
						</th>
						<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">
							Size
						</th>
						<th class="px-6 py-3 text-right text-xs font-medium uppercase text-slate-500">
							Actions
						</th>
					</tr>
				</thead>
				<tbody class="divide-y divide-slate-100">
					{#each filteredDocuments as doc}
						{@const category = getCategory(doc.category_id)}
						<tr class="hover:bg-slate-50">
							<td class="px-6 py-4">
								<div class="flex items-center gap-3">
									<FileText class="h-5 w-5 text-monaco-600" />
									<div>
										<p class="font-medium text-slate-900">{doc.title}</p>
										<p class="text-xs text-slate-500">{doc.file_name}</p>
									</div>
								</div>
							</td>
							<td class="px-6 py-4 text-sm text-slate-500">
								{category?.display_name || '-'}
							</td>
							<td class="px-6 py-4 text-sm text-slate-500">
								{formatDate(doc.created_at)}
							</td>
							<td class="px-6 py-4 text-sm text-slate-500">
								{formatFileSize(doc.file_size)}
							</td>
							<td class="px-6 py-4 text-right">
								<div class="flex justify-end gap-2">
									<a
										href={doc.active_url}
										target="_blank"
										rel="noopener noreferrer"
										class="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
									>
										<Eye class="h-4 w-4" />
									</a>
									<a
										href={doc.active_url}
										download={doc.file_name}
										class="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-monaco-600"
									>
										<Download class="h-4 w-4" />
									</a>
								</div>
							</td>
						</tr>
					{/each}
				</tbody>
			</table>
		</div>
	{/if}
</div>
