<script lang="ts">
	import {
		FileText,
		Upload,
		Search,
		Trash2,
		Download,
		Eye,
		X,
		FolderOpen,
		FolderPlus,
		Calendar,
		User,
		Filter,
		ArrowUpRight
	} from 'lucide-svelte';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { enhance } from '$app/forms';
	import { invalidateAll, goto } from '$app/navigation';
	import {
		DocumentPreviewModal,
		FolderItem,
		FolderBreadcrumbs,
		CreateFolderModal
	} from '$lib/components/documents';

	let { data, form } = $props();
	const { documents, folders, categories, member, currentFolderId, breadcrumbs } = data;

	let searchQuery = $state('');
	let selectedCategory = $state<string | null>(null);
	let showUploadModal = $state(false);
	let showDeleteConfirm = $state(false);
	let showCreateFolderModal = $state(false);
	let showPreviewModal = $state(false);
	let documentToDelete = $state<any>(null);
	let documentToPreview = $state<any>(null);
	let previewUrl = $state<string>('');
	let isSubmitting = $state(false);
	let selectedFile = $state<File | null>(null);
	let dragOver = $state(false);
	let renamingFolder = $state<any>(null);
	let showRenameFolderModal = $state(false);

	// Filter documents
	const filteredDocuments = $derived(
		(documents || []).filter((doc: any) => {
			const matchesSearch =
				!searchQuery ||
				doc.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
				doc.description?.toLowerCase().includes(searchQuery.toLowerCase());
			const matchesCategory = !selectedCategory || doc.category_id === selectedCategory;
			return matchesSearch && matchesCategory;
		})
	);

	// Filter folders
	const filteredFolders = $derived(
		(folders || []).filter((folder: any) => {
			if (!searchQuery) return true;
			return folder.name.toLowerCase().includes(searchQuery.toLowerCase());
		})
	);

	// Check permissions
	const canEdit = $derived(member?.role === 'board' || member?.role === 'admin');
	const canDelete = $derived(member?.role === 'admin');

	// 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 visibility label
	function getVisibilityLabel(visibility: string) {
		switch (visibility) {
			case 'public':
				return { label: 'Public', color: 'bg-green-100 text-green-700' };
			case 'members':
				return { label: 'Members', color: 'bg-blue-100 text-blue-700' };
			case 'board':
				return { label: 'Board', color: 'bg-purple-100 text-purple-700' };
			case 'admin':
				return { label: 'Admin', color: 'bg-red-100 text-red-700' };
			default:
				return { label: visibility, color: 'bg-slate-100 text-slate-700' };
		}
	}

	// Handle file selection
	function handleFileSelect(e: Event) {
		const input = e.target as HTMLInputElement;
		if (input.files && input.files[0]) {
			selectedFile = input.files[0];
		}
	}

	// Handle drag and drop
	function handleDrop(e: DragEvent) {
		e.preventDefault();
		dragOver = false;
		if (e.dataTransfer?.files && e.dataTransfer.files[0]) {
			selectedFile = e.dataTransfer.files[0];
		}
	}

	function handleDragOver(e: DragEvent) {
		e.preventDefault();
		dragOver = true;
	}

	function handleDragLeave(e: DragEvent) {
		e.preventDefault();
		dragOver = false;
	}

	// Navigate to folder
	function navigateToFolder(folderId: string | null) {
		if (folderId) {
			goto(`/board/documents?folder=${folderId}`);
		} else {
			goto('/board/documents');
		}
	}

	// Confirm delete
	function confirmDelete(doc: any) {
		documentToDelete = doc;
		showDeleteConfirm = true;
	}

	// Open preview
	async function openPreview(doc: any) {
		documentToPreview = doc;
		// Get the preview URL (uses active_url which is computed based on storage setting)
		previewUrl = doc.active_url || doc.file_path;
		showPreviewModal = true;
	}

	// Reset upload form
	function resetUploadForm() {
		selectedFile = null;
		showUploadModal = false;
	}

	// Handle folder rename
	function handleRenameFolder(folder: any) {
		renamingFolder = folder;
		showRenameFolderModal = true;
	}

	// Handle folder delete
	function handleDeleteFolder(folder: any) {
		documentToDelete = { ...folder, isFolder: true };
		showDeleteConfirm = true;
	}
</script>

<svelte:head>
	<title>Document Management | Monaco USA</title>
</svelte:head>

<div class="space-y-6">
	<!-- Header -->
	<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">Document Management</h1>
			<p class="text-slate-500">Upload and manage association documents</p>
		</div>

		<div class="flex gap-2">
			{#if canEdit}
				<button
					onclick={() => (showCreateFolderModal = true)}
					class="flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 font-medium text-slate-700 hover:bg-slate-50"
				>
					<FolderPlus class="h-5 w-5" />
					New Folder
				</button>
			{/if}

			<button
				onclick={() => (showUploadModal = true)}
				class="flex items-center gap-2 rounded-lg bg-monaco-600 px-4 py-2 font-medium text-white hover:bg-monaco-700"
			>
				<Upload class="h-5 w-5" />
				Upload Document
			</button>
		</div>
	</div>

	{#if form?.error}
		<div class="rounded-lg bg-red-50 p-4 text-sm text-red-600">
			{form.error}
		</div>
	{/if}

	{#if form?.success}
		<div class="rounded-lg bg-green-50 p-4 text-sm text-green-600">
			{form.success}
		</div>
	{/if}

	<!-- Breadcrumbs -->
	{#if breadcrumbs && breadcrumbs.length > 0}
		<div class="glass-card p-4">
			<FolderBreadcrumbs {breadcrumbs} onNavigate={navigateToFolder} />
		</div>
	{/if}

	<!-- Filters -->
	<div class="glass-card p-4">
		<div class="flex flex-col gap-4 sm:flex-row sm:items-center">
			<div class="relative flex-1">
				<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 and folders..."
					bind:value={searchQuery}
					class="h-10 pl-9"
				/>
			</div>

			<select
				bind:value={selectedCategory}
				class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm"
			>
				<option value={null}>All Categories</option>
				{#each categories as category}
					<option value={category.id}>{category.display_name}</option>
				{/each}
			</select>
		</div>
	</div>

	<!-- Folders Grid -->
	{#if filteredFolders.length > 0}
		<div>
			<h2 class="mb-3 text-sm font-medium text-slate-500 uppercase tracking-wide">Folders</h2>
			<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
				{#each filteredFolders as folder}
					<FolderItem
						{folder}
						{canEdit}
						{canDelete}
						onNavigate={navigateToFolder}
						onRename={handleRenameFolder}
						onDelete={handleDeleteFolder}
					/>
				{/each}
			</div>
		</div>
	{/if}

	<!-- Documents Table -->
	<div class="glass-card overflow-hidden">
		{#if filteredFolders.length === 0 && filteredDocuments.length === 0}
			<div class="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">
					{currentFolderId ? 'This folder is empty' : 'No documents found'}
				</h3>
				<p class="mt-1 text-slate-500">
					{searchQuery || selectedCategory
						? 'Try adjusting your search or filters.'
						: currentFolderId
							? 'Upload documents or create subfolders to get started.'
							: 'Upload your first document to get started.'}
				</p>
			</div>
		{:else if filteredDocuments.length === 0}
			<div class="flex flex-col items-center justify-center p-8 text-center">
				<FileText class="mb-4 h-12 w-12 text-slate-300" />
				<h3 class="text-base font-medium text-slate-900">No documents in this location</h3>
				<p class="mt-1 text-sm text-slate-500">
					Documents you upload here will appear in this list.
				</p>
			</div>
		{:else}
			<div>
				<h2 class="px-6 py-3 text-sm font-medium text-slate-500 uppercase tracking-wide bg-slate-50/50">
					Documents ({filteredDocuments.length})
				</h2>
				<div class="overflow-x-auto">
					<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">
									Visibility
								</th>
								<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">
									Uploaded
								</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 visInfo = getVisibilityLabel(doc.visibility)}
								<tr class="hover:bg-slate-50">
									<td class="px-6 py-4">
										<button
											onclick={() => openPreview(doc)}
											class="flex items-center gap-3 text-left hover:text-monaco-600 transition-colors"
										>
											<FileText class="h-5 w-5 text-monaco-600 flex-shrink-0" />
											<div class="min-w-0">
												<p class="font-medium text-slate-900 truncate">{doc.title}</p>
												<p class="text-xs text-slate-500 truncate">
													{doc.file_name} ({formatFileSize(doc.file_size)})
												</p>
											</div>
										</button>
									</td>
									<td class="px-6 py-4 text-sm text-slate-500">
										{doc.category?.display_name || '-'}
									</td>
									<td class="px-6 py-4">
										<form
											method="POST"
											action="?/updateVisibility"
											use:enhance={() => {
												return async ({ update }) => {
													await invalidateAll();
													await update();
												};
											}}
											class="inline"
										>
											<input type="hidden" name="document_id" value={doc.id} />
											<select
												name="visibility"
												value={doc.visibility}
												onchange={(e) => e.currentTarget.form?.requestSubmit()}
												class="rounded-lg border-0 bg-transparent py-1 pr-8 text-xs font-medium cursor-pointer hover:bg-slate-100 {visInfo.color}"
											>
												<option value="public">Public</option>
												<option value="members">Members</option>
												<option value="board">Board</option>
												<option value="admin">Admin</option>
											</select>
										</form>
									</td>
									<td class="px-6 py-4">
										<div class="text-sm">
											<p class="text-slate-900">{formatDate(doc.created_at)}</p>
											<p class="text-xs text-slate-500">
												by {doc.uploader?.first_name} {doc.uploader?.last_name}
											</p>
										</div>
									</td>
									<td class="px-6 py-4 text-right">
										<div class="flex justify-end gap-2">
											<button
												onclick={() => openPreview(doc)}
												class="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
												title="Preview"
											>
												<Eye class="h-4 w-4" />
											</button>
											<a
												href={doc.active_url || doc.file_path}
												download={doc.file_name}
												class="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-monaco-600"
												title="Download"
											>
												<Download class="h-4 w-4" />
											</a>
											{#if canDelete}
												<button
													onclick={() => confirmDelete(doc)}
													class="rounded p-1.5 text-slate-400 hover:bg-red-100 hover:text-red-600"
													title="Delete"
												>
													<Trash2 class="h-4 w-4" />
												</button>
											{/if}
										</div>
									</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</div>
		{/if}
	</div>
</div>

<!-- Create Folder Modal -->
{#if showCreateFolderModal}
	<CreateFolderModal
		parentFolderId={currentFolderId}
		onClose={() => (showCreateFolderModal = false)}
	/>
{/if}

<!-- Document Preview Modal -->
{#if showPreviewModal && documentToPreview}
	<DocumentPreviewModal
		document={documentToPreview}
		{previewUrl}
		onClose={() => {
			showPreviewModal = false;
			documentToPreview = null;
		}}
	/>
{/if}

<!-- Upload Modal -->
{#if showUploadModal}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-lg p-6">
			<div class="mb-6 flex items-center justify-between">
				<h2 class="text-lg font-semibold text-slate-900">Upload Document</h2>
				<button onclick={resetUploadForm} class="rounded p-1 hover:bg-slate-100">
					<X class="h-5 w-5 text-slate-500" />
				</button>
			</div>

			<form
				method="POST"
				action="?/upload"
				enctype="multipart/form-data"
				use:enhance={() => {
					isSubmitting = true;
					return async ({ update, result }) => {
						await invalidateAll();
						isSubmitting = false;
						if (result.type === 'success') {
							resetUploadForm();
						}
						await update();
					};
				}}
				class="space-y-4"
			>
				<!-- Hidden folder ID -->
				{#if currentFolderId}
					<input type="hidden" name="folder_id" value={currentFolderId} />
				{/if}

				<!-- File Drop Zone -->
				<div
					class="relative rounded-lg border-2 border-dashed p-8 text-center transition-colors
						{dragOver
						? 'border-monaco-500 bg-monaco-50'
						: 'border-slate-300 hover:border-slate-400'}"
					ondrop={handleDrop}
					ondragover={handleDragOver}
					ondragleave={handleDragLeave}
					role="button"
					tabindex="0"
				>
					<input
						type="file"
						name="file"
						id="file"
						class="absolute inset-0 cursor-pointer opacity-0"
						onchange={handleFileSelect}
						accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv,.json,.jpg,.jpeg,.png,.webp,.gif"
					/>

					{#if selectedFile}
						<div class="flex items-center justify-center gap-3">
							<FileText class="h-10 w-10 text-monaco-600" />
							<div class="text-left">
								<p class="font-medium text-slate-900">{selectedFile.name}</p>
								<p class="text-sm text-slate-500">{formatFileSize(selectedFile.size)}</p>
							</div>
							<button
								type="button"
								onclick={(e) => {
									e.stopPropagation();
									selectedFile = null;
								}}
								class="rounded p-1 hover:bg-slate-100"
							>
								<X class="h-5 w-5 text-slate-400" />
							</button>
						</div>
					{:else}
						<Upload class="mx-auto h-10 w-10 text-slate-400" />
						<p class="mt-2 text-sm font-medium text-slate-900">
							Drag and drop or click to select
						</p>
						<p class="mt-1 text-xs text-slate-500">
							PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, TXT, CSV, JSON, JPG, PNG, GIF (max 50MB)
						</p>
					{/if}
				</div>

				<div>
					<Label for="title">Title *</Label>
					<Input type="text" id="title" name="title" required class="mt-1" />
				</div>

				<div>
					<Label for="description">Description</Label>
					<textarea
						id="description"
						name="description"
						rows="2"
						class="mt-1 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
						placeholder="Brief description of the document..."
					></textarea>
				</div>

				<div class="grid gap-4 sm:grid-cols-2">
					<div>
						<Label for="category_id">Category</Label>
						<select
							id="category_id"
							name="category_id"
							class="mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm"
						>
							<option value="">Select category...</option>
							{#each categories as category}
								<option value={category.id}>{category.display_name}</option>
							{/each}
						</select>
					</div>

					<div>
						<Label for="visibility">Visibility</Label>
						<select
							id="visibility"
							name="visibility"
							class="mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm"
						>
							<option value="members">Members Only</option>
							<option value="board">Board Only</option>
							<option value="admin">Admin Only</option>
							<option value="public">Public</option>
						</select>
					</div>
				</div>

				<div class="flex gap-3 pt-4">
					<button
						type="button"
						onclick={resetUploadForm}
						class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
					>
						Cancel
					</button>
					<button
						type="submit"
						disabled={isSubmitting || !selectedFile}
						class="flex flex-1 items-center justify-center gap-2 rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{#if isSubmitting}
							<div class="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"
							></div>
							Uploading...
						{:else}
							<Upload class="h-4 w-4" />
							Upload Document
						{/if}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}

<!-- Delete Confirmation Modal -->
{#if showDeleteConfirm && documentToDelete}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-md p-6">
			<div class="mb-4 flex items-center gap-3 text-red-600">
				<Trash2 class="h-6 w-6" />
				<h3 class="text-lg font-semibold">
					Delete {documentToDelete.isFolder ? 'Folder' : 'Document'}
				</h3>
			</div>

			<p class="mb-4 text-slate-600">
				Are you sure you want to delete <strong>{documentToDelete.title || documentToDelete.name}</strong>? This action cannot be undone.
			</p>

			<div class="flex gap-3">
				<button
					onclick={() => {
						showDeleteConfirm = false;
						documentToDelete = null;
					}}
					class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
				>
					Cancel
				</button>
				<form
					method="POST"
					action={documentToDelete.isFolder ? '?/deleteFolder' : '?/delete'}
					use:enhance={() => {
						return async ({ update, result }) => {
							if (result.type === 'success') {
								showDeleteConfirm = false;
								documentToDelete = null;
							}
							await invalidateAll();
							await update();
						};
					}}
					class="flex-1"
				>
					<input
						type="hidden"
						name={documentToDelete.isFolder ? 'folder_id' : 'document_id'}
						value={documentToDelete.id}
					/>
					<button
						type="submit"
						class="w-full rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700"
					>
						Delete {documentToDelete.isFolder ? 'Folder' : 'Document'}
					</button>
				</form>
			</div>
		</div>
	</div>
{/if}

<!-- Rename Folder Modal -->
{#if showRenameFolderModal && renamingFolder}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-md p-6">
			<div class="mb-6 flex items-center justify-between">
				<h2 class="text-lg font-semibold text-slate-900">Rename Folder</h2>
				<button
					onclick={() => {
						showRenameFolderModal = false;
						renamingFolder = null;
					}}
					class="rounded p-1 hover:bg-slate-100"
				>
					<X class="h-5 w-5 text-slate-500" />
				</button>
			</div>

			<form
				method="POST"
				action="?/renameFolder"
				use:enhance={() => {
					isSubmitting = true;
					return async ({ update, result }) => {
						await invalidateAll();
						isSubmitting = false;
						if (result.type === 'success') {
							showRenameFolderModal = false;
							renamingFolder = null;
						}
						await update();
					};
				}}
				class="space-y-4"
			>
				<input type="hidden" name="folder_id" value={renamingFolder.id} />

				<div>
					<Label for="rename-name">Folder Name</Label>
					<Input
						type="text"
						id="rename-name"
						name="name"
						value={renamingFolder.name}
						required
						class="mt-1"
					/>
				</div>

				<div class="flex gap-3 pt-4">
					<button
						type="button"
						onclick={() => {
							showRenameFolderModal = false;
							renamingFolder = null;
						}}
						class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
					>
						Cancel
					</button>
					<button
						type="submit"
						disabled={isSubmitting}
						class="flex flex-1 items-center justify-center gap-2 rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{#if isSubmitting}
							<div class="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"></div>
							Saving...
						{:else}
							Save
						{/if}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}
