<script lang="ts">
	import { onMount, tick } from 'svelte';
	import { helpApi, type HelpArticle } from '$lib/api/help';
	import * as Card from '$lib/components/ui/card/index.js';
	import { Button } from '$lib/components/ui/button/index.js';
	import * as Dialog from '$lib/components/ui/dialog/index.js';
	import * as AlertDialog from '$lib/components/ui/alert-dialog/index.js';
	import { Input } from '$lib/components/ui/input/index.js';
	import { Textarea } from '$lib/components/ui/textarea/index.js';
	import { Label } from '$lib/components/ui/label/index.js';
	import {
		Plus,
		Trash2,
		Edit,
		Loader2,
		Search,
		Book,
		Image as ImageIcon,
		FileText,
		Video,
		FileCode
	} from 'lucide-svelte';
	import { toast } from 'svelte-sonner';

	let articles: HelpArticle[] = $state([]);
	let loading = $state(true);
	let searchTerm = $state('');
	const HUB_MODE = import.meta.env.VITE_HUB_MODE === 'true';

	// 🛡️ Seguridad y Permisos
	import { currentUser, userHasPermission } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

	const canView = $derived(userHasPermission($currentUser, 'help_center.view'));
	// Solo los ADMIN de Keycloak pueden crear/editar/borrar en el Hub
	const isAdmin = $derived($currentUser?.roles?.includes('admin') || false);
	const canCreate = $derived(HUB_MODE && isAdmin);
	const canEdit = $derived(HUB_MODE && isAdmin);
	const canDelete = $derived(HUB_MODE && isAdmin);

	// Modals state
	let showCreateModal = $state(false);
	let showEditModal = $state(false);
	let showDeleteDialog = $state(false);
	let processing = $state(false);

	let selectedArticle: HelpArticle | null = $state(null);

	// Form state
	let formValues = $state({
		title: '',
		slug: '',
		content: '',
		last_editor: 'Admin',
		category: 'General',
		order: 0
	});

	// Derived state: Grouped by Category with prioritization for Manuals
	const groupedArticles = $derived.by(() => {
		const filtered = articles
			.filter(
				(a) =>
					a.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
					a.content.toLowerCase().includes(searchTerm.toLowerCase()) ||
					(a.category || 'General').toLowerCase().includes(searchTerm.toLowerCase())
			)
			.sort((a, b) => {
				// Prioritize Manuales category
				const catA = (a.category || 'General').toLowerCase();
				const catB = (b.category || 'General').toLowerCase();
				if (catA.includes('manual') && !catB.includes('manual')) return -1;
				if (!catA.includes('manual') && catB.includes('manual')) return 1;
				return (a.order || 0) - (b.order || 0);
			});

		const groups: Record<string, HelpArticle[]> = {};
		filtered.forEach((article) => {
			const cat = article.category || 'General';
			if (!groups[cat]) groups[cat] = [];
			groups[cat].push(article);
		});
		return groups;
	});

	onMount(async () => {
		await loadArticles();
	});

	async function loadArticles() {
		loading = true;
		try {
			articles = await helpApi.listArticles();
		} catch (e: any) {
			toast.error('Error al cargar artículos: ' + e.message);
		} finally {
			loading = false;
		}
	}

	function handleCreate() {
		window.location.href = '/dashboard/help-center/editor/new';
	}

	function openEdit(article: HelpArticle) {
		window.location.href = `/dashboard/help-center/editor/${article.uuid}`;
	}

	async function handleDelete() {
		if (!selectedArticle) return;
		processing = true;
		try {
			await helpApi.deleteArticle(selectedArticle.uuid);
			toast.success('Capítulo eliminado');
			showDeleteDialog = false;
			await loadArticles();
		} catch (e: any) {
			toast.error('Error: ' + e.message);
		} finally {
			processing = false;
		}
	}

	function openDelete(article: HelpArticle) {
		selectedArticle = article;
		showDeleteDialog = true;
	}
</script>

{#if !canView}
	<div class="flex h-full items-center justify-center">
		<ErrorState status={403} />
	</div>
{:else}
	<div class="flex h-full flex-col space-y-6 rounded-xl bg-muted/10 p-4">
	<!-- Page Header -->
	<div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
		<div>
			<h1 class="flex items-center gap-2 text-3xl font-bold tracking-tight text-primary">
				<Book class="h-8 w-8" />
				Biblioteca de Conocimiento
			</h1>
			<p class="text-muted-foreground">Manuales, Guías y Documentación del Sistema.</p>
		</div>
		<div class="flex items-center gap-2">
			{#if canCreate}
				<Button href="/dashboard/help-center/editor/new" class="shadow-lg">
					<Plus class="mr-2 h-4 w-4" />
					Nuevo Capítulo
				</Button>
			{/if}
		</div>
	</div>

	<!-- Search -->
	<div class="relative max-w-lg">
		<Search class="absolute top-3 left-3 h-4 w-4 text-muted-foreground" />
		<Input
			type="search"
			placeholder="Buscar en la biblioteca..."
			class="h-10 border-muted-foreground/20 bg-background pl-10"
			bind:value={searchTerm}
		/>
	</div>

	<!-- Content: Shelves -->
	<div class="flex-1 space-y-8 overflow-auto pr-2">
		{#if loading}
			<div class="flex h-40 items-center justify-center">
				<Loader2 class="h-10 w-10 animate-spin text-primary" />
			</div>
		{:else if Object.keys(groupedArticles).length === 0}
			<div class="flex flex-col items-center justify-center py-20 text-muted-foreground">
				<Book class="mb-4 h-16 w-16 opacity-20" />
				<p>La biblioteca está vacía.</p>
			</div>
		{:else}
			{#each Object.entries(groupedArticles) as [category, groupArticles]}
				<div class="space-y-4">
					<h2
						class="flex items-center gap-2 border-b pb-2 text-xl font-semibold text-foreground/80"
					>
						<span
							class="rounded bg-primary/10 px-2 py-1 text-sm tracking-wide text-primary uppercase"
							>{category}</span
						>
					</h2>
					<div class="grid gap-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
						{#each groupArticles as article}
							<Card.Root
								class="group relative flex h-full flex-col overflow-hidden border-muted-foreground/10 bg-background transition-all duration-300 hover:border-primary/50 hover:shadow-xl"
							>
								<div
									class="absolute top-0 left-0 h-full w-1 bg-primary/0 transition-all group-hover:bg-primary"
								></div>
								<Card.Header class="pb-2">
									<Card.Title
										class="line-clamp-2 flex items-center gap-2 text-lg transition-colors group-hover:text-primary"
									>
										{#if article.content_type === 'pdf'}
											<FileText class="h-5 w-5 text-red-500" />
										{:else if article.content_type === 'video'}
											<Video class="h-5 w-5 text-blue-500" />
										{:else if article.content_type === 'article'}
											<Book class="h-5 w-5 text-primary" />
										{:else}
											<FileCode class="h-5 w-5 text-muted-foreground" />
										{/if}
										{article.title}
									</Card.Title>
									<Card.Description class="text-xs">
										{new Date(article.updated_at).toLocaleDateString()}
									</Card.Description>
								</Card.Header>
								<Card.Content class="flex-grow pt-2">
									{#if article.content_type === 'article'}
										<div class="prose prose-sm line-clamp-3 text-sm text-muted-foreground">
											{@html (article.content || '').replace(/<[^>]*>?/gm, '').substring(0, 150)}...
										</div>
									{:else}
										<div class="flex flex-col gap-1 text-xs text-muted-foreground">
											<p>Formato: {article.mime_type || 'Desconocido'}</p>
											{#if article.file_size}
												<p>Tamaño: {(article.file_size / 1024 / 1024).toFixed(2)} MB</p>
											{/if}
										</div>
									{/if}
								</Card.Content>
								<Card.Footer class="flex items-center justify-between border-t bg-muted/5 pt-4">
									<Button variant="ghost" size="sm" href={`/dashboard/help-center/${article.uuid}`}>
										{#if article.content_type === 'video'}
											Ver
										{:else if article.content_type === 'article'}
											Leer
										{:else}
											Abrir
										{/if}
									</Button>
									<div class="flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
										{#if canEdit}
											<Button
												variant="ghost"
												size="icon"
												class="h-7 w-7"
												href={`/dashboard/help-center/editor/${article.uuid}`}
											>
												<Edit class="h-3 w-3" />
											</Button>
										{/if}
										{#if canDelete}
											<Button
												variant="ghost"
												size="icon"
												class="h-7 w-7 text-destructive"
												onclick={() => openDelete(article)}
											>
												<Trash2 class="h-3 w-3" />
											</Button>
										{/if}
									</div>
								</Card.Footer>
							</Card.Root>
						{/each}
					</div>
				</div>
			{/each}
		{/if}
	</div>
</div>

<!-- Delete Confirmation -->
<AlertDialog.Root bind:open={showDeleteDialog}>
	<AlertDialog.Content>
		<AlertDialog.Header>
			<AlertDialog.Title>¿Eliminar capítulo?</AlertDialog.Title>
			<AlertDialog.Description>
				Se eliminará permanentemente "{selectedArticle?.title}".
			</AlertDialog.Description>
		</AlertDialog.Header>
		<AlertDialog.Footer>
			<AlertDialog.Cancel onclick={() => (showDeleteDialog = false)}>Cancelar</AlertDialog.Cancel>
			<AlertDialog.Action
				class="text-destructive-foreground bg-destructive hover:bg-destructive/90"
				onclick={handleDelete}
			>
				{#if processing}<Loader2 class="mr-2 h-4 w-4 animate-spin" />{/if}
				Eliminar
			</AlertDialog.Action>
		</AlertDialog.Footer>
	</AlertDialog.Content>
</AlertDialog.Root>
{/if}
