<script lang="ts">
	import * as Dialog from "$lib/components/ui/dialog";
	import * as Table from "$lib/components/ui/table";
	import { Button } from "$lib/components/ui/button";
	import { Input } from "$lib/components/ui/input";
	import { Search, Loader2 } from "lucide-svelte";
	import { getIdentifiers, type Identifier } from "$lib/api/dashboard/a76/general_catalogs/identifiers";
	import { onMount } from "svelte";
	import { companyStore } from '$lib/stores/company.svelte';
	import { m } from '$lib/i18n/messages';

	let {
		open = $bindable(false),
		onSelect,
		onClear
	}: {
		open: boolean;
		onSelect: (identifier: Identifier) => void;
		onClear?: () => void;
	} = $props();

	let identifiers = $state<Identifier[]>([]);
	let loading = $state(false);
	let searchTerm = $state("");

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

		loading = true;
		try {
			// Using a large limit for now to avoid complex pagination in the selector
			const res = await getIdentifiers(1, 1000, companyId);
			if (res.data) {
				identifiers = res.data.items || [];
			}
		} catch (error) {
			console.error("Error loading identifiers:", error);
		} finally {
			loading = false;
		}
	}

	onMount(() => {
		loadIdentifiers();
	});

	const filteredIdentifiers = $derived(
		identifiers.filter(i => 
			i.code.toLowerCase().includes(searchTerm.toLowerCase()) || 
			(i.description?.toLowerCase().includes(searchTerm.toLowerCase()) ?? false)
		)
	);

	function handleSelect(identifier: Identifier) {
		onSelect(identifier);
		open = false;
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[600px] h-[600px] flex flex-col p-0 text-xs">
		<Dialog.Header class="px-6 pt-6 pb-4 shrink-0">
			<Dialog.Title>{m.invoice_selectors_identifier_catalog_title()}</Dialog.Title>
			<Dialog.Description>
				{m.invoice_selectors_identifier_catalog_description()}
			</Dialog.Description>
		</Dialog.Header>

		<div class="px-6 pb-4 shrink-0">
			<div class="relative">
				<Search class="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
				<Input
					type="search"
					placeholder={m.invoice_selectors_identifier_catalog_search_placeholder()}
					class="pl-9 h-9 text-xs"
					bind:value={searchTerm}
				/>
			</div>
		</div>

		<div class="flex-1 overflow-y-auto px-6 pb-6">
			{#if loading}
				<div class="flex h-full items-center justify-center">
					<Loader2 class="h-6 w-6 animate-spin text-muted-foreground" />
				</div>
			{:else}
				<Table.Root>
					<Table.Header class="sticky top-0 bg-background z-10">
						<Table.Row>
							<Table.Head class="w-16">{m.invoice_selectors_identifier_catalog_column_code()}</Table.Head>
							<Table.Head>{m.invoice_selectors_identifier_catalog_column_description()}</Table.Head>
							<Table.Head class="w-16">{m.invoice_selectors_identifier_catalog_column_level()}</Table.Head>
						</Table.Row>
					</Table.Header>
					<Table.Body>
						{#each filteredIdentifiers as item}
							<Table.Row 
								class="cursor-pointer hover:bg-muted" 
								onclick={() => handleSelect(item)}
							>
								<Table.Cell class="font-bold">{item.code}</Table.Cell>
								<Table.Cell>{item.description || '-'}</Table.Cell>
								<Table.Cell>{item.level || '-'}</Table.Cell>
							</Table.Row>
						{:else}
							<Table.Row>
								<Table.Cell colspan={3} class="h-24 text-center text-muted-foreground">
									{m.invoice_selectors_identifier_catalog_empty()}
								</Table.Cell>
							</Table.Row>
						{/each}
					</Table.Body>
				</Table.Root>
			{/if}
		</div>
		<div class="flex shrink-0 items-center justify-end gap-2 border-t bg-background px-6 py-4">
			{#if onClear}
				<Button variant="ghost" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
			{/if}
			<Button variant="outline" onclick={() => (open = false)}>Cerrar</Button>
		</div>
	</Dialog.Content>
</Dialog.Root>
