<script lang="ts">
	import { onMount } from 'svelte';
	import { invoke } from '@tauri-apps/api/core';
	import { activeKnowledgeHints } from '$lib/stores/app';

	// Typen für Wissensbasis
	interface KnowledgeEntry {
		id: number;
		category: string;
		title: string;
		content: string;
		tags: string | null;
		priority: number;
		status: string;
		related_ids: string | null;
		source: string | null;
		created_at: string;
		updated_at: string;
	}

	interface SearchResult {
		entry: KnowledgeEntry;
		relevance: number;
	}

	interface CategoryInfo {
		name: string;
		count: number;
	}

	// State
	let searchQuery = $state('');
	let selectedCategory = $state<string | null>(null);
	let results = $state<SearchResult[]>([]);
	let categories = $state<CategoryInfo[]>([]);
	let loading = $state(false);
	let connected = $state(false);
	let connectionError = $state('');
	let selectedEntry = $state<KnowledgeEntry | null>(null);

	// "Das merken" Dialog
	let showSaveDialog = $state(false);
	let newEntry = $state({
		category: 'pattern',
		title: '',
		content: '',
		tags: '',
		priority: 2,
		source: 'Claude Desktop'
	});

	// Kategorie-Icons
	const categoryIcons: Record<string, string> = {
		dolibarr: '📊',
		fints: '🏦',
		ids: '🔗',
		pattern: '📋',
		projekt: '📁',
		setup: '⚙️'
	};

	// Prioritäts-Labels
	const priorityLabels: Record<number, string> = {
		1: 'Kritisch',
		2: 'Hoch',
		3: 'Normal',
		4: 'Niedrig'
	};

	onMount(async () => {
		await testConnection();
		if (connected) {
			await loadCategories();
			await loadRecent();
		}
	});

	async function testConnection() {
		try {
			const result: string = await invoke('test_knowledge_connection');
			connected = true;
			connectionError = '';
			console.log('✅ Wissensbasis:', result);
		} catch (err) {
			connected = false;
			connectionError = String(err);
			console.error('❌ Wissensbasis-Verbindung fehlgeschlagen:', err);
		}
	}

	async function loadCategories() {
		try {
			categories = await invoke('get_knowledge_categories');
		} catch (err) {
			console.error('Fehler beim Laden der Kategorien:', err);
		}
	}

	async function loadRecent() {
		loading = true;
		try {
			const entries: KnowledgeEntry[] = await invoke('get_recent_knowledge', {
				limit: 10,
				category: selectedCategory
			});
			results = entries.map(entry => ({ entry, relevance: 0 }));
		} catch (err) {
			console.error('Fehler beim Laden:', err);
		}
		loading = false;
	}

	async function search() {
		if (!searchQuery.trim()) {
			await loadRecent();
			return;
		}

		loading = true;
		try {
			results = await invoke('search_knowledge', {
				query: searchQuery,
				category: selectedCategory,
				limit: 20
			});
		} catch (err) {
			console.error('Suchfehler:', err);
		}
		loading = false;
	}

	async function saveKnowledge() {
		if (!newEntry.title.trim() || !newEntry.content.trim()) {
			return;
		}

		try {
			const id: number = await invoke('save_knowledge', {
				entry: {
					category: newEntry.category,
					title: newEntry.title,
					content: newEntry.content,
					tags: newEntry.tags || null,
					priority: newEntry.priority,
					source: newEntry.source
				}
			});
			console.log('✅ Gespeichert mit ID:', id);

			// Dialog schließen und zurücksetzen
			showSaveDialog = false;
			newEntry = {
				category: 'pattern',
				title: '',
				content: '',
				tags: '',
				priority: 2,
				source: 'Claude Desktop'
			};

			// Kategorien und Ergebnisse neu laden
			await loadCategories();
			await loadRecent();
		} catch (err) {
			console.error('Fehler beim Speichern:', err);
		}
	}

	function handleKeydown(event: KeyboardEvent) {
		if (event.key === 'Enter' && !event.shiftKey) {
			search();
		}
		if (event.key === 'Escape') {
			showSaveDialog = false;
			selectedEntry = null;
		}
	}

	function formatDate(dateStr: string): string {
		const date = new Date(dateStr);
		return date.toLocaleDateString('de-DE', {
			day: '2-digit',
			month: '2-digit',
			year: '2-digit'
		});
	}

	function truncate(text: string, maxLength: number): string {
		if (text.length <= maxLength) return text;
		return text.slice(0, maxLength) + '...';
	}
</script>

<svelte:window onkeydown={handleKeydown} />

<div class="knowledge-panel">
	<div class="panel-header">
		<h2>📚 Wissensbasis</h2>
		{#if connected}
			<span class="connection-status connected">Verbunden</span>
		{:else}
			<span class="connection-status disconnected" title={connectionError}>Offline</span>
		{/if}
	</div>

	{#if !connected}
		<div class="error-box">
			<p>Verbindung zur Wissensbasis fehlgeschlagen.</p>
			<p class="error-detail">{connectionError}</p>
			<button class="btn-retry" onclick={testConnection}>🔄 Erneut verbinden</button>
		</div>
	{:else}
		<!-- Suchleiste -->
		<div class="search-bar">
			<input
				type="text"
				placeholder="Wissensbasis durchsuchen..."
				bind:value={searchQuery}
				onkeydown={handleKeydown}
			/>
			<button class="btn-search" onclick={search} disabled={loading}>
				{#if loading}⏳{:else}🔍{/if}
			</button>
		</div>

		<!-- Kategorie-Filter -->
		<div class="category-filter">
			<button
				class="category-chip"
				class:active={selectedCategory === null}
				onclick={() => { selectedCategory = null; loadRecent(); }}
			>
				Alle
			</button>
			{#each categories as cat}
				<button
					class="category-chip"
					class:active={selectedCategory === cat.name}
					onclick={() => { selectedCategory = cat.name; loadRecent(); }}
				>
					{categoryIcons[cat.name] || '📦'} {cat.name} ({cat.count})
				</button>
			{/each}
		</div>

		<!-- Aktive Wissens-Hints (bei Tool-Aufrufen) -->
		{#if $activeKnowledgeHints.length > 0}
			<div class="active-hints">
				<div class="hints-header">
					<span class="hints-icon">💡</span>
					<span class="hints-title">Aktive Hints</span>
					<button class="btn-clear-hints" onclick={() => activeKnowledgeHints.set([])}>✕</button>
				</div>
				{#each $activeKnowledgeHints as hint}
					<div class="hint-item">
						<div class="hint-title">{categoryIcons[hint.category] || '📦'} {hint.title}</div>
						<div class="hint-preview">{truncate(hint.content, 150)}</div>
					</div>
				{/each}
			</div>
		{/if}

		<!-- Ergebnisliste -->
		<div class="results-list">
			{#if results.length === 0}
				<div class="empty-state">
					{#if searchQuery}
						Keine Treffer für "{searchQuery}"
					{:else}
						Keine Einträge vorhanden
					{/if}
				</div>
			{:else}
				{#each results as { entry, relevance }}
					<button
						class="result-item"
						onclick={() => selectedEntry = entry}
						class:selected={selectedEntry?.id === entry.id}
					>
						<div class="result-header">
							<span class="result-icon">{categoryIcons[entry.category] || '📦'}</span>
							<span class="result-title">{entry.title}</span>
							{#if relevance > 0}
								<span class="relevance-badge">{relevance.toFixed(1)}</span>
							{/if}
						</div>
						<div class="result-preview">{truncate(entry.content, 100)}</div>
						<div class="result-meta">
							<span class="result-category">{entry.category}</span>
							{#if entry.tags}
								<span class="result-tags">{entry.tags}</span>
							{/if}
							<span class="result-date">{formatDate(entry.updated_at)}</span>
						</div>
					</button>
				{/each}
			{/if}
		</div>

		<!-- Aktionen -->
		<div class="actions">
			<button class="btn-save" onclick={() => showSaveDialog = true}>
				💡 Das merken
			</button>
		</div>
	{/if}
</div>

<!-- Detail-Ansicht (Modal) -->
{#if selectedEntry}
	<div class="modal-overlay" onclick={() => selectedEntry = null}>
		<div class="modal-content" onclick={(e) => e.stopPropagation()}>
			<div class="modal-header">
				<h3>{categoryIcons[selectedEntry.category] || '📦'} {selectedEntry.title}</h3>
				<button class="btn-close" onclick={() => selectedEntry = null}>✕</button>
			</div>
			<div class="modal-body">
				<div class="entry-meta">
					<span class="meta-item">
						<strong>Kategorie:</strong> {selectedEntry.category}
					</span>
					<span class="meta-item">
						<strong>Priorität:</strong> {priorityLabels[selectedEntry.priority]}
					</span>
					{#if selectedEntry.tags}
						<span class="meta-item">
							<strong>Tags:</strong> {selectedEntry.tags}
						</span>
					{/if}
					{#if selectedEntry.source}
						<span class="meta-item">
							<strong>Quelle:</strong> {selectedEntry.source}
						</span>
					{/if}
					<span class="meta-item">
						<strong>Aktualisiert:</strong> {formatDate(selectedEntry.updated_at)}
					</span>
				</div>
				<div class="entry-content">
					{selectedEntry.content}
				</div>
			</div>
		</div>
	</div>
{/if}

<!-- "Das merken" Dialog -->
{#if showSaveDialog}
	<div class="modal-overlay" onclick={() => showSaveDialog = false}>
		<div class="modal-content save-dialog" onclick={(e) => e.stopPropagation()}>
			<div class="modal-header">
				<h3>💡 Neues Wissen speichern</h3>
				<button class="btn-close" onclick={() => showSaveDialog = false}>✕</button>
			</div>
			<div class="modal-body">
				<div class="form-group">
					<label for="save-title">Titel</label>
					<input
						id="save-title"
						type="text"
						bind:value={newEntry.title}
						placeholder="Kurzer, prägnanter Titel"
					/>
				</div>

				<div class="form-row">
					<div class="form-group">
						<label for="save-category">Kategorie</label>
						<select id="save-category" bind:value={newEntry.category}>
							<option value="pattern">📋 Pattern</option>
							<option value="dolibarr">📊 Dolibarr</option>
							<option value="fints">🏦 FinTS</option>
							<option value="setup">⚙️ Setup</option>
							<option value="projekt">📁 Projekt</option>
							<option value="ids">🔗 IDs</option>
						</select>
					</div>

					<div class="form-group">
						<label for="save-priority">Priorität</label>
						<select id="save-priority" bind:value={newEntry.priority}>
							<option value={1}>1 - Kritisch</option>
							<option value={2}>2 - Hoch</option>
							<option value={3}>3 - Normal</option>
							<option value={4}>4 - Niedrig</option>
						</select>
					</div>
				</div>

				<div class="form-group">
					<label for="save-content">Inhalt (Markdown)</label>
					<textarea
						id="save-content"
						bind:value={newEntry.content}
						placeholder="Beschreibung, Code-Snippets, Erkenntnisse..."
						rows="8"
					></textarea>
				</div>

				<div class="form-group">
					<label for="save-tags">Tags (kommagetrennt)</label>
					<input
						id="save-tags"
						type="text"
						bind:value={newEntry.tags}
						placeholder="z.B. rust, async, debugging"
					/>
				</div>

				<div class="form-actions">
					<button class="btn-cancel" onclick={() => showSaveDialog = false}>
						Abbrechen
					</button>
					<button
						class="btn-confirm"
						onclick={saveKnowledge}
						disabled={!newEntry.title.trim() || !newEntry.content.trim()}
					>
						💾 Speichern
					</button>
				</div>
			</div>
		</div>
	</div>
{/if}

<style>
	.knowledge-panel {
		padding: var(--spacing-md);
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.panel-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: var(--spacing-md);
	}

	.panel-header h2 {
		font-size: 1rem;
		font-weight: 600;
	}

	.connection-status {
		font-size: 0.7rem;
		padding: 2px 8px;
		border-radius: var(--radius-sm);
		font-weight: 500;
	}

	.connection-status.connected {
		background: var(--success);
		color: white;
	}

	.connection-status.disconnected {
		background: var(--error);
		color: white;
	}

	.error-box {
		background: rgba(239, 68, 68, 0.1);
		border: 1px solid var(--error);
		border-radius: var(--radius-md);
		padding: var(--spacing-md);
		text-align: center;
	}

	.error-detail {
		font-size: 0.75rem;
		color: var(--text-secondary);
		margin: var(--spacing-sm) 0;
	}

	.btn-retry {
		padding: var(--spacing-xs) var(--spacing-md);
		background: var(--error);
		color: white;
		border-radius: var(--radius-sm);
		font-size: 0.875rem;
	}

	.search-bar {
		display: flex;
		gap: var(--spacing-xs);
		margin-bottom: var(--spacing-sm);
	}

	.search-bar input {
		flex: 1;
		padding: var(--spacing-sm);
		background: var(--bg-secondary);
		border: 1px solid var(--border);
		border-radius: var(--radius-sm);
		font-size: 0.875rem;
		color: var(--text-primary);
	}

	.search-bar input::placeholder {
		color: var(--text-secondary);
	}

	.btn-search {
		padding: var(--spacing-sm) var(--spacing-md);
		background: var(--accent);
		color: white;
		border-radius: var(--radius-sm);
		font-size: 1rem;
	}

	.btn-search:disabled {
		background: var(--bg-tertiary);
	}

	.category-filter {
		display: flex;
		flex-wrap: wrap;
		gap: var(--spacing-xs);
		margin-bottom: var(--spacing-md);
	}

	.category-chip {
		padding: 2px 8px;
		background: var(--bg-secondary);
		border: 1px solid var(--border);
		border-radius: var(--radius-sm);
		font-size: 0.7rem;
		color: var(--text-secondary);
		transition: all 0.2s ease;
	}

	.category-chip:hover {
		background: var(--bg-tertiary);
	}

	.category-chip.active {
		background: var(--accent);
		color: white;
		border-color: var(--accent);
	}

	.results-list {
		flex: 1;
		overflow-y: auto;
		display: flex;
		flex-direction: column;
		gap: var(--spacing-xs);
	}

	.empty-state {
		text-align: center;
		padding: var(--spacing-xl);
		color: var(--text-secondary);
		font-size: 0.875rem;
	}

	.result-item {
		padding: var(--spacing-sm);
		background: var(--bg-secondary);
		border: 1px solid var(--border);
		border-radius: var(--radius-sm);
		text-align: left;
		transition: all 0.2s ease;
		cursor: pointer;
	}

	.result-item:hover {
		border-color: var(--accent);
	}

	.result-item.selected {
		border-color: var(--accent);
		background: rgba(59, 130, 246, 0.1);
	}

	.result-header {
		display: flex;
		align-items: center;
		gap: var(--spacing-xs);
		margin-bottom: var(--spacing-xs);
	}

	.result-icon {
		font-size: 0.9rem;
	}

	.result-title {
		flex: 1;
		font-weight: 600;
		font-size: 0.875rem;
		color: var(--text-primary);
	}

	.relevance-badge {
		font-size: 0.65rem;
		padding: 1px 4px;
		background: var(--accent);
		color: white;
		border-radius: var(--radius-sm);
	}

	.result-preview {
		font-size: 0.75rem;
		color: var(--text-secondary);
		line-height: 1.4;
		margin-bottom: var(--spacing-xs);
	}

	.result-meta {
		display: flex;
		gap: var(--spacing-sm);
		font-size: 0.65rem;
		color: var(--text-secondary);
	}

	.result-category {
		background: var(--bg-tertiary);
		padding: 1px 4px;
		border-radius: 2px;
	}

	.result-tags {
		opacity: 0.7;
	}

	.result-date {
		margin-left: auto;
	}

	.actions {
		margin-top: var(--spacing-md);
	}

	.btn-save {
		width: 100%;
		padding: var(--spacing-sm) var(--spacing-md);
		background: var(--success);
		color: white;
		border-radius: var(--radius-md);
		font-size: 0.875rem;
		font-weight: 500;
		transition: all 0.2s ease;
	}

	.btn-save:hover {
		filter: brightness(1.1);
	}

	/* Modal */
	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.7);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 100;
	}

	.modal-content {
		background: var(--bg-primary);
		border: 1px solid var(--border);
		border-radius: var(--radius-lg);
		max-width: 600px;
		width: 90%;
		max-height: 80vh;
		overflow: hidden;
		display: flex;
		flex-direction: column;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: var(--spacing-md);
		border-bottom: 1px solid var(--border);
	}

	.modal-header h3 {
		font-size: 1rem;
		font-weight: 600;
	}

	.btn-close {
		width: 28px;
		height: 28px;
		display: flex;
		align-items: center;
		justify-content: center;
		background: var(--bg-secondary);
		border-radius: var(--radius-sm);
		font-size: 0.875rem;
		color: var(--text-secondary);
	}

	.btn-close:hover {
		background: var(--bg-tertiary);
		color: var(--text-primary);
	}

	.modal-body {
		padding: var(--spacing-md);
		overflow-y: auto;
		flex: 1;
	}

	.entry-meta {
		display: flex;
		flex-wrap: wrap;
		gap: var(--spacing-sm);
		margin-bottom: var(--spacing-md);
		font-size: 0.75rem;
	}

	.meta-item {
		background: var(--bg-secondary);
		padding: 2px 8px;
		border-radius: var(--radius-sm);
	}

	.meta-item strong {
		color: var(--text-secondary);
		font-weight: 500;
	}

	.entry-content {
		font-size: 0.875rem;
		line-height: 1.6;
		white-space: pre-wrap;
		font-family: var(--font-mono);
	}

	/* Save Dialog */
	.save-dialog {
		max-width: 500px;
	}

	.form-group {
		margin-bottom: var(--spacing-md);
	}

	.form-group label {
		display: block;
		font-size: 0.75rem;
		font-weight: 500;
		color: var(--text-secondary);
		margin-bottom: var(--spacing-xs);
	}

	.form-group input,
	.form-group select,
	.form-group textarea {
		width: 100%;
		padding: var(--spacing-sm);
		background: var(--bg-secondary);
		border: 1px solid var(--border);
		border-radius: var(--radius-sm);
		font-size: 0.875rem;
		color: var(--text-primary);
	}

	.form-group textarea {
		resize: vertical;
		font-family: var(--font-mono);
	}

	.form-row {
		display: flex;
		gap: var(--spacing-md);
	}

	.form-row .form-group {
		flex: 1;
	}

	.form-actions {
		display: flex;
		gap: var(--spacing-sm);
		justify-content: flex-end;
		margin-top: var(--spacing-md);
	}

	.btn-cancel {
		padding: var(--spacing-sm) var(--spacing-md);
		background: var(--bg-secondary);
		border: 1px solid var(--border);
		border-radius: var(--radius-sm);
		font-size: 0.875rem;
	}

	.btn-confirm {
		padding: var(--spacing-sm) var(--spacing-md);
		background: var(--success);
		color: white;
		border-radius: var(--radius-sm);
		font-size: 0.875rem;
		font-weight: 500;
	}

	.btn-confirm:disabled {
		background: var(--bg-tertiary);
		color: var(--text-secondary);
	}

	/* Aktive Wissens-Hints */
	.active-hints {
		background: linear-gradient(135deg, rgba(250, 204, 21, 0.1) 0%, rgba(234, 179, 8, 0.05) 100%);
		border: 1px solid rgba(250, 204, 21, 0.3);
		border-radius: var(--radius-md);
		padding: var(--spacing-sm);
		margin-bottom: var(--spacing-md);
	}

	.hints-header {
		display: flex;
		align-items: center;
		gap: var(--spacing-xs);
		margin-bottom: var(--spacing-sm);
	}

	.hints-icon {
		font-size: 1rem;
	}

	.hints-title {
		flex: 1;
		font-size: 0.75rem;
		font-weight: 600;
		color: var(--text-primary);
		text-transform: uppercase;
		letter-spacing: 0.5px;
	}

	.btn-clear-hints {
		width: 20px;
		height: 20px;
		display: flex;
		align-items: center;
		justify-content: center;
		background: transparent;
		border-radius: var(--radius-sm);
		font-size: 0.75rem;
		color: var(--text-secondary);
		opacity: 0.6;
	}

	.btn-clear-hints:hover {
		opacity: 1;
		background: rgba(0, 0, 0, 0.1);
	}

	.hint-item {
		padding: var(--spacing-xs) var(--spacing-sm);
		background: rgba(255, 255, 255, 0.5);
		border-radius: var(--radius-sm);
		margin-bottom: var(--spacing-xs);
	}

	.hint-item:last-child {
		margin-bottom: 0;
	}

	.hint-title {
		font-size: 0.8rem;
		font-weight: 500;
		color: var(--text-primary);
		margin-bottom: 2px;
	}

	.hint-preview {
		font-size: 0.7rem;
		color: var(--text-secondary);
		line-height: 1.4;
	}

	:global(.dark) .hint-item {
		background: rgba(0, 0, 0, 0.2);
	}
</style>
