<script lang="ts">
	import { SETTINGS_METADATA } from './settings-metadata';
	import SettingFormField from './SettingFormField.svelte';
	import { Input } from '$lib/components/ui/input';
	import { Search, FilterX } from 'lucide-svelte';
	import { fade } from 'svelte/transition';

	export let category: string;
	export let currentData: any = {};
	export let onUpdate: (data: any) => void;

	let searchQuery = '';
	
	// Local state to manage edits before final save
	let formData: any = { ...currentData };

	// Update local state when category changes
	$: {
		formData = { ...currentData };
	}

	function handleFieldChange(key: string, value: any) {
		formData[key] = value;
		onUpdate(formData); // Propagate changes upward
	}

	// Filter fields based on metadata and search query
	$: availableFields = SETTINGS_METADATA[category] || Object.keys(currentData);
	$: filteredFields = availableFields.filter(f => 
		f.toLowerCase().includes(searchQuery.toLowerCase())
	);

	// Derived grouped fields for UI organization
	$: hasResults = filteredFields.length > 0;
</script>

<div class="space-y-6 flex flex-col h-full overflow-hidden">
	<!-- Search/Filter Bar -->
	<div class="relative group mx-2">
		<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/20 group-focus-within:text-primary transition-colors" />
		<Input 
			placeholder="Buscar parámetro en {category}..." 
			bind:value={searchQuery}
			class="pl-10 bg-black/40 border-white/5 h-10 focus-visible:ring-primary/20"
		/>
	</div>

	<!-- Fields Grid -->
	<div class="flex-1 overflow-y-auto px-2 custom-scrollbar pr-4">
		{#if hasResults}
			<div class="grid grid-cols-1 md:grid-cols-2 gap-3 pb-8">
				{#each filteredFields as field (field)}
					<div in:fade={{ duration: 150 }}>
						<SettingFormField 
							key={field} 
							value={formData[field]} 
							onChange={(val) => handleFieldChange(field, val)} 
						/>
					</div>
				{/each}
			</div>
		{:else}
			<div class="flex flex-col items-center justify-center h-48 text-white/20 border-2 border-dashed border-white/5 rounded-2xl mx-2">
				<FilterX class="w-12 h-12 mb-4 opacity-50" />
				<p class="text-xs uppercase tracking-widest">No se encontraron parámetros</p>
			</div>
		{/if}
	</div>
</div>

<style>
	.custom-scrollbar::-webkit-scrollbar {
		width: 4px;
	}
	.custom-scrollbar::-webkit-scrollbar-thumb {
		background: rgba(255, 255, 255, 0.05);
		border-radius: 10px;
	}
</style>
