<script lang="ts">
	import { page } from '$app/stores';
	import { browser } from '$app/environment';
	import { onMount, tick } from 'svelte';
	import { helpApi, type HelpArticle } from '$lib/api/help';
	import { Button } from '$lib/components/ui/button/index.js';
	import { Input } from '$lib/components/ui/input/index.js';
	import { Label } from '$lib/components/ui/label/index.js';
	import { Textarea } from '$lib/components/ui/textarea/index.js';
	import {
		Loader2,
		Save,
		ArrowLeft,
		Image as ImageIcon,
		Bold,
		Italic,
		Link as LinkIcon,
		List,
		Heading1,
		Heading2,
		FileText,
		Video as VideoIcon,
		FileCode,
		Upload,
		HelpCircle
	} from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import { marked } from 'marked';
	import DOMPurify from 'dompurify';
	import { getFileNameFromPath } from '$lib/utils';

	// Helper to resolve an API path from the DB (e.g., /api/uploads/...) to a full URL pointing to the local backend.
	function resolveAssetUrl(url: string | undefined): string {
		if (!url) return '';
		if (url.startsWith('http://') || url.startsWith('https://')) return url;
		
		// Fallback to empty string if VITE_API_URL is missing
		// @ts-ignore
		const apiUrl = import.meta.env.VITE_API_URL || '';
		const base = apiUrl.replace(/\/$/, '');
		const cleanUrl = url.replace(/^\/api\//, '/'); 
		return `${base}${cleanUrl}`;
	}

	let article = $state<HelpArticle | null>(null);
	let loading = $state(true);
	let processing = $state(false);

	// Editor State
	let title = $state('');
	let slug = $state('');
	let content = $state('');
	let category = $state('General');
	let order = $state(0);
	let last_editor = $state('Admin');
	let content_type = $state('article');
	let file_url = $state('');
	let file_size = $state<number | undefined>(undefined);
	let mime_type = $state('');
	let context_path = $state('');
	let tags = $state('');

	// Preview State
	let showPreview = $state(true);
	const HUB_MODE = import.meta.env.VITE_HUB_MODE === 'true';

	onMount(async () => {
		// Proteccion: Solo el Hub puede editar/crear
		if (!HUB_MODE) {
			window.location.href = '/dashboard/help-center';
			return;
		}

		const uuid = $page.params.uuid as string;
		if (uuid === 'new') {
			loading = false;
			// Pre-rellenar context_path si viene en la URL
			const urlParams = new URLSearchParams(window.location.search);
			if (urlParams.has('context_path')) {
				context_path = urlParams.get('context_path') || '';
			}
			return;
		}

		try {
			article = await helpApi.getArticle(uuid);
			if (article) {
				title = article.title;
				slug = article.slug;
				content = article.content || '';
				category = article.category || 'General';
				order = article.order || 0;
				last_editor = article.last_editor || 'Admin';
				content_type = article.content_type || 'article';
				file_url = article.file_url || '';
				file_size = article.file_size ?? undefined;
				mime_type = article.mime_type || '';
				context_path = article.context_path || '';
				tags = article.tags || '';
			}
		} catch (e: any) {
			toast.error('Error al cargar artículo: ' + e.message);
		} finally {
			loading = false;
		}
	});

	async function handleSave() {
		processing = true;
		try {
			const data = {
				title,
				slug,
				content,
				last_editor,
				category,
				order,
				content_type,
				file_url,
				file_size,
				mime_type,
				context_path,
				tags
			};

			// Auto-generate slug if missing
			if (!data.slug) {
				data.slug = data.title
					.toLowerCase()
					.replace(/ /g, '-')
					.replace(/[^\w-]+/g, '');
				slug = data.slug;
			}

			const uuid = $page.params.uuid as string;
			if (uuid === 'new') {
				const newArticle = await helpApi.createArticle(data);
				toast.success('Capítulo creado');
				// Redirect to edit mode or list? For now, stay here but update URL would be ideal.
				// simpler to just go back to list or reload.
				// Let's redirect to edit mode of this new UUID to avoid duplicates on re-save
				window.location.href = `/dashboard/help-center/editor/${newArticle.uuid}`;
			} else {
				await helpApi.updateArticle(uuid, data);
				toast.success('Cambios guardados');
			}
		} catch (e: any) {
			toast.error('Error al guardar: ' + e.message);
		} finally {
			processing = false;
		}
	}

	function insertText(prefix: string, suffix: string = '') {
		const textarea = document.getElementById('markdown-editor') as HTMLTextAreaElement;
		if (!textarea) return;

		const start = textarea.selectionStart;
		const end = textarea.selectionEnd;
		const text = textarea.value;
		const selection = text.substring(start, end);

		const before = text.substring(0, start);
		const after = text.substring(end);

		content = `${before}${prefix}${selection}${suffix}${after}`;

		// Restore focus and selection
		tick().then(() => {
			textarea.focus();
			textarea.setSelectionRange(start + prefix.length, end + prefix.length);
		});
	}

	async function handleImageUpload(file: File) {
		const tid = toast.loading('Subiendo imagen...');
		processing = true;
		try {
			const result = await helpApi.uploadImage(file);
			const imageMarkdown = `\n![${file.name}](${result.url})\n`;
			insertText(imageMarkdown);
			toast.success('Imagen insertada', { id: tid });
		} catch (e: any) {
			toast.error('Error al subir: ' + e.message, { id: tid });
		} finally {
			processing = false;
		}
	}

	async function handleAssetUpload(file: File) {
		const tid = toast.loading(`Subiendo ${file.name}...`);
		processing = true;
		try {
			const result = await helpApi.uploadAsset(file);
			file_url = result.url;
			file_size = result.size;
			mime_type = result.mime_type;

			// Auto-set title if empty
			if (!title) {
				title = file.name.split('.').shift() || 'Sin Título';
			}
			if (!slug) {
				slug = title.toLowerCase().replace(/[^\w]+/g, '-');
			}

			// Auto-infer content type if not set or article
			if (content_type === 'article') {
				if (mime_type === 'application/pdf') content_type = 'pdf';
				else if (mime_type.startsWith('video/')) content_type = 'video';
				else content_type = 'document';
			}

			toast.success('Archivo subido correctamente', { id: tid });
		} catch (e: any) {
			toast.error('Error al subir archivo: ' + e.message, { id: tid });
		} finally {
			processing = false;
		}
	}

	function handleDrop(e: DragEvent) {
		e.preventDefault();
		const files = e.dataTransfer?.files;
		if (files && files.length > 0) {
			const file = files[0];
			if (file.type.startsWith('image/')) {
				handleImageUpload(file);
			}
		}
	}

	function renderMarkdown(text: string) {
		if (!text) return '';
		try {
			const html = marked.parse(text) as string;
			
			// Rewrite image src and link hrefs to point to the local backend
			let resolvedHtml = html.replace(/src="([^"]+)"/g, (match, src) => {
				return `src="${resolveAssetUrl(src)}"`;
			});
			resolvedHtml = resolvedHtml.replace(/href="(\/api\/uploads\/[^"]+)"/g, (match, href) => {
				return `href="${resolveAssetUrl(href)}"`;
			});

			if (browser && typeof window !== 'undefined') {
				return DOMPurify.sanitize(resolvedHtml);
			}
			return resolvedHtml;
		} catch (e) {
			console.error("Markdown parsing error in editor:", e);
			return '';
		}
	}
</script>

<div class="flex h-screen flex-col overflow-hidden bg-background">
	<!-- Top Bar -->
	<header class="z-10 flex items-center justify-between border-b bg-card px-6 py-3">
		<div class="flex items-center gap-4">
			<Button variant="ghost" size="sm" href="/dashboard/help-center">
				<ArrowLeft class="mr-2 h-4 w-4" />
				Volver
			</Button>
			<h1 class="max-w-md truncate text-lg font-semibold">
				{title || 'Sin Título'}
			</h1>
		</div>
		<div class="flex items-center gap-2">
			<Button variant="outline" size="sm" onclick={() => (showPreview = !showPreview)}>
				{showPreview ? 'Ocultar Vista Previa' : 'Ver Vista Previa'}
			</Button>
			<Button onclick={handleSave} disabled={processing || !title}>
				{#if processing}<Loader2 class="mr-2 h-4 w-4 animate-spin" />{/if}
				<Save class="mr-2 h-4 w-4" />
				Guardar
			</Button>
		</div>
	</header>

	<!-- Main Editor Area -->
	<div class="flex flex-1 overflow-hidden">
		<!-- Metadata Sidebar (Left) - Collapsible or Fixed width -->
		<aside class="hidden w-64 overflow-y-auto border-r bg-muted/10 p-4 lg:block">
			<h3 class="mb-4 text-sm font-semibold tracking-wider text-muted-foreground uppercase">
				Configuración
			</h3>
			<div class="space-y-4">
				<div class="grid gap-2">
					<Label for="title">Título</Label>
					<Input id="title" bind:value={title} placeholder="Ej: Introducción" />
				</div>
				<div class="grid gap-2 border-t pt-4">
					<Label for="slug">Identificador (Slug)</Label>
					<Input id="slug" bind:value={slug} placeholder="ej-titulo-articulo" />
					<p class="text-[10px] text-muted-foreground">Se autogenera del título si se deja vacío.</p>
				</div>
				<div class="grid gap-2 border-t pt-4">
					<Label for="type">Tipo de Contenido</Label>
					<select
						id="type"
						bind:value={content_type}
						class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
					>
						<option value="article">Artículo (Markdown)</option>
						<option value="pdf">PDF</option>
						<option value="video">Video</option>
						<option value="document">Otro Documento</option>
					</select>
				</div>

				<details class="group border-t pt-4">
					<summary class="flex cursor-pointer items-center justify-between text-xs font-semibold tracking-wider text-muted-foreground uppercase hover:text-primary transition-colors">
						Opciones Avanzadas
						<HelpCircle size={14} class="opacity-50 group-open:rotate-180 transition-transform" />
					</summary>
					<div class="space-y-4 pt-4">
						<div class="grid gap-2">
							<Label for="category">Categoría</Label>
							<Input id="category" bind:value={category} placeholder="Ej: General" />
						</div>
						<div class="grid gap-2">
							<Label for="order">Orden</Label>
							<Input id="order" type="number" bind:value={order} />
						</div>
						<div class="grid gap-2">
							<Label for="context_path" class="flex items-center gap-1">
								Ruta Contextual
							</Label>
							<Input id="context_path" bind:value={context_path} placeholder="Ej: /dashboard/..." />
							<p class="text-[10px] text-muted-foreground">URL donde aparecerá este artículo.</p>
						</div>
						<div class="grid gap-2">
							<Label for="tags">Etiquetas</Label>
							<Input id="tags" bind:value={tags} placeholder="Ej: facturas, mermas" />
						</div>
					</div>
				</details>
			</div>
		</aside>

		<!-- Split View -->
		<main class="flex flex-1 overflow-hidden">
			{#if content_type === 'article'}
				<!-- Editor -->
				<div class="group relative flex flex-1 flex-col border-r">
					<!-- Toolbar -->
					<div class="flex items-center gap-1 border-b bg-background p-2">
						<Button
							variant="ghost"
							size="icon"
							class="h-8 w-8"
							onclick={() => insertText('**', '**')}
							title="Negrita"
						>
							<Bold class="h-4 w-4" />
						</Button>
						<Button
							variant="ghost"
							size="icon"
							class="h-8 w-8"
							onclick={() => insertText('*', '*')}
							title="Cursiva"
						>
							<Italic class="h-4 w-4" />
						</Button>
						<div class="mx-1 h-4 w-px bg-border"></div>
						<Button
							variant="ghost"
							size="icon"
							class="h-8 w-8"
							onclick={() => insertText('# ')}
							title="Título 1"
						>
							<Heading1 class="h-4 w-4" />
						</Button>
						<Button
							variant="ghost"
							size="icon"
							class="h-8 w-8"
							onclick={() => insertText('## ')}
							title="Título 2"
						>
							<Heading2 class="h-4 w-4" />
						</Button>
						<div class="mx-1 h-4 w-px bg-border"></div>
						<Button
							variant="ghost"
							size="icon"
							class="h-8 w-8"
							onclick={() => insertText('- ')}
							title="Lista"
						>
							<List class="h-4 w-4" />
						</Button>
						<Button
							variant="ghost"
							size="icon"
							class="h-8 w-8"
							onclick={() => insertText('[texto](url)')}
							title="Enlace"
						>
							<LinkIcon class="h-4 w-4" />
						</Button>
						<label
							class="inline-flex h-8 w-8 cursor-pointer items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50"
							title="Subir Imagen"
						>
							<ImageIcon class="h-4 w-4" />
							<input
								type="file"
								accept="image/*"
								class="hidden"
								onchange={(e) => {
									const target = e.target as HTMLInputElement;
									if (target.files?.length) handleImageUpload(target.files[0]);
								}}
							/>
						</label>
					</div>

					<textarea
						id="markdown-editor"
						bind:value={content}
						class="w-full flex-1 resize-none bg-background p-8 font-mono text-sm leading-relaxed outline-none"
						placeholder="# Empieza a escribir aquí..."
						ondrop={(e: DragEvent) => handleDrop(e)}
						ondragover={(e: DragEvent) => e.preventDefault()}
					></textarea>

					<!-- Dropping Hint -->
					<div
						class="pointer-events-none absolute inset-0 m-4 hidden items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/10 opacity-0 transition-opacity group-hover:flex"
					>
						<p class="font-medium text-primary">Arrastra imágenes aquí</p>
					</div>
				</div>

				<!-- Preview -->
				{#if showPreview}
					<div class="w-1/2 flex-1 overflow-y-auto border-l bg-muted/5 p-8">
						<div class="prose max-w-none prose-slate dark:prose-invert">
							{@html renderMarkdown(content)}
						</div>
					</div>
				{/if}
			{:else}
				<!-- Asset Upload View -->
				<div class="flex flex-1 flex-col items-center justify-center bg-muted/5 p-12">
					<div class="w-full max-w-2xl space-y-8 text-center">
						<div class="flex flex-col items-center gap-4">
							{#if content_type === 'pdf'}
								<div class="rounded-full bg-red-100 p-6 dark:bg-red-900/20">
									<FileText class="h-16 w-16 text-red-500" />
								</div>
								<h2 class="text-2xl font-bold">Configuración de PDF</h2>
							{:else if content_type === 'video'}
								<div class="rounded-full bg-blue-100 p-6 dark:bg-blue-900/20">
									<VideoIcon class="h-16 w-16 text-blue-500" />
								</div>
								<h2 class="text-2xl font-bold">Configuración de Video</h2>
							{:else}
								<div class="rounded-full bg-primary/10 p-6">
									<FileCode class="h-16 w-16 text-primary" />
								</div>
								<h2 class="text-2xl font-bold">Configuración de Documento</h2>
							{/if}
							<p class="text-muted-foreground">Sube el archivo que deseas asociar a este título.</p>
						</div>

						{#if file_url}
							<div class="relative flex flex-col gap-4 rounded-xl border bg-card p-6 shadow-sm">
								<div class="flex items-center gap-4">
									<div class="rounded bg-muted p-2">
										<FileCode class="h-6 w-6" />
									</div>
									<div class="flex-1 text-left">
										<p class="font-medium">Archivo Cargado</p>
										<p class="truncate text-xs text-muted-foreground">
											{getFileNameFromPath(file_url)}
										</p>
										<p class="font-mono text-xs">
											{mime_type} • {file_size ? (file_size / 1024 / 1024).toFixed(2) : '??'} MB
										</p>
									</div>
								</div>
								<div class="flex gap-2">
									<Button variant="outline" class="flex-1" href={resolveAssetUrl(file_url)} target="_blank">
										Ver Archivo
									</Button>
									<label
										class="flex flex-1 cursor-pointer items-center justify-center rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground"
									>
										Cambiar Archivo
										<input
											type="file"
											class="hidden"
											onchange={(e) => {
												const target = e.target as HTMLInputElement;
												if (target.files?.length) handleAssetUpload(target.files[0]);
											}}
										/>
									</label>
								</div>
							</div>
						{:else}
							<label
								class="flex h-64 w-full cursor-pointer flex-col items-center justify-center gap-4 rounded-2xl border-2 border-dashed border-muted-foreground/20 bg-muted/20 transition-colors hover:border-primary/50 hover:bg-primary/5"
							>
								<div class="flex flex-col items-center gap-2">
									<div class="rounded-full bg-background p-4 shadow-sm">
										<Upload class="h-8 w-8 text-primary" />
									</div>
									<span class="font-medium">Selecciona un archivo</span>
									<span class="text-xs text-muted-foreground">O arrastra y suelta aquí</span>
								</div>
								<input
									type="file"
									class="hidden"
									onchange={(e) => {
										const target = e.target as HTMLInputElement;
										if (target.files?.length) handleAssetUpload(target.files[0]);
									}}
								/>
							</label>
						{/if}
					</div>
				</div>
			{/if}
		</main>
	</div>
</div>
