<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Search, Loader2, Layers, Tag, Box } from 'lucide-svelte';
	// Importamos la interfaz corregida
	import { materialTypesApi, type MaterialType } from '$lib/api/dashboard/a76/material-types';
	import { companyStore } from '$lib/stores/company.svelte';

	// --- PROPS ---
	let {
		open = $bindable(false),
		onSelect,
		onClear
	}: {
		open: boolean;
		onSelect: (item: MaterialType) => void;
		onClear?: () => void;
	} = $props();

	let items = $state<MaterialType[]>([]);
	let loading = $state(false);
	let searchTerm = $state('');
	let loaded = $state(false);

	let filteredItems = $derived(
		items.filter(
			(i) =>
				i.key.toLowerCase().includes(searchTerm.toLowerCase()) ||
				i.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
				i.type.toLowerCase().includes(searchTerm.toLowerCase())
		)
	);

	$effect(() => {
		if (open && !loaded) loadMaterials();
	});

	async function loadMaterials() {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;

		loading = true;
		try {
			const res = await materialTypesApi.list(companyId, 1, 100);

			const responseData = (res as any).data || res;

			if (responseData && responseData.items) {
				items = responseData.items;
				loaded = true;
			} else {
				console.error('Estructura inesperada:', responseData);
			}
		} catch (e) {
			console.error('Error cargando materiales:', e);
		} finally {
			loading = false;
		}
	}

	function handleSelect(item: MaterialType) {
		if (onSelect) onSelect(item);
		open = false;
	}

	function getCategoryIcon(type: string) {
		if (type.includes('PRODUCTOS')) return Box;
		if (type.includes('ACTIVO')) return Layers;
		return Tag;
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="z-[300] flex max-h-[80vh] flex-col sm:max-w-[650px]">
		<Dialog.Header>
			<Dialog.Title>Seleccionar Tipo de Material</Dialog.Title>
			<Dialog.Description>Catálogo general.</Dialog.Description>
		</Dialog.Header>

		<div class="relative my-2 w-full">
			<Search class="absolute top-2.5 left-2.5 h-4 w-4 text-muted-foreground" />
			<Input type="search" placeholder="Buscar..." class="pl-9" bind:value={searchTerm} />
		</div>

		<div class="min-h-[300px] flex-1 overflow-y-auto rounded-md border">
			{#if loading}
				<div class="flex h-48 flex-col items-center justify-center gap-2 text-muted-foreground">
					<Loader2 class="h-8 w-8 animate-spin text-primary" />
					<p>Cargando catálogo...</p>
				</div>
			{:else if filteredItems.length === 0}
				<div class="flex h-48 flex-col items-center justify-center text-muted-foreground">
					<p>No se encontraron resultados.</p>
				</div>
			{:else}
				<table class="w-full text-sm">
					<thead class="bg-muted/50 backdrop-blur-sm">
						<tr class="border-b text-left">
							<th class="w-[80px] p-3 font-medium text-muted-foreground">Clave</th>
							<th class="p-3 font-medium text-muted-foreground">Descripción</th>
							<th class="w-[120px] p-3 font-medium text-muted-foreground">Tipo</th>
						</tr>
					</thead>
					<tbody>
						{#each filteredItems as item}
							{@const Icon = getCategoryIcon(item.type)}
							<tr
								class="cursor-pointer border-b transition-all duration-200 hover:bg-primary/10 hover:shadow-inner active:bg-primary/20"
								onclick={() => handleSelect(item)}
							>
								<td class="p-3 font-mono font-bold text-primary">{item.key}</td>

								<td class="p-3 font-medium">{item.description}</td>

								<td class="p-3">
									<div class="flex items-center gap-1 text-xs text-muted-foreground">
										<Icon class="h-3 w-3" />
										{item.type}
									</div>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			{/if}
		</div>
		<Dialog.Footer>
			{#if onClear}
				<Button variant="ghost" class="mr-auto" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
			{/if}
			<Button variant="outline" onclick={() => (open = false)}>Cancelar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
