<script lang="ts">
	import * as Dialog from '$lib/components/ui/dialog';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Search, LoaderCircle, X, Check } from 'lucide-svelte';
	import {
		customsSectionsApi,
		type CustomsSection
	} from '$lib/api/dashboard/reference_data/customs_sections';
	import { m } from '$lib/i18n/messages';
	import { toast } from 'svelte-sonner';

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

	let searchQuery = $state('');
	let sections = $state<CustomsSection[]>([]);
	let loading = $state(false);
	let selectedSection = $state<CustomsSection | null>(null);

	async function loadSections() {
		loading = true;
		try {
			const response = await customsSectionsApi.list(1, 100);
			if (response?.data?.items) {
				sections = response.data.items;
			}
		} catch (error) {
			console.error('Error loading customs sections:', error);
			toast.error(m.invoice_selectors_port_selector_loading());
		} finally {
			loading = false;
		}
	}

	$effect(() => {
		if (open) {
			loadSections();
		}
	});

	const filteredSections = $derived(
		sections.filter(
			(s) =>
				s.customs_code.toLowerCase().includes(searchQuery.toLowerCase()) ||
				s.section_name.toLowerCase().includes(searchQuery.toLowerCase())
		)
	);

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

<Dialog.Root bind:open>
	<Dialog.Content class="max-w-2xl">
		<Dialog.Header>
			<Dialog.Title>{m.invoice_selectors_port_selector_title()}</Dialog.Title>
			<Dialog.Description>{m.invoice_selectors_port_selector_description()}</Dialog.Description>
		</Dialog.Header>

		<div class="space-y-4 py-4">
			<div class="relative">
				<Search class="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
				<Input placeholder={m.invoice_selectors_port_selector_search_placeholder()} class="pl-10" bind:value={searchQuery} />
			</div>

			<div class="max-h-[400px] overflow-y-auto rounded-md border">
				{#if loading}
					<div class="flex items-center justify-center py-10">
						<LoaderCircle class="h-8 w-8 animate-spin text-primary" />
					</div>
				{:else if filteredSections.length > 0}
					<table class="w-full text-sm">
						<thead class="sticky top-0 bg-muted">
							<tr>
								<th class="p-2 text-left font-medium">{m.invoice_selectors_port_selector_column_code()}</th>
								<th class="p-2 text-left font-medium">{m.invoice_selectors_port_selector_column_name()}</th>
								<th class="w-10 p-2"></th>
							</tr>
						</thead>
						<tbody class="divide-y">
							{#each filteredSections as section}
								<tr class="cursor-pointer hover:bg-muted/50" onclick={() => handleSelect(section)}>
									<td class="p-2 font-mono">{section.customs_code}</td>
									<td class="p-2">{section.section_name}</td>
									<td class="p-2">
										<Button variant="ghost" size="icon" class="h-8 w-8">
											<Check class="h-4 w-4 text-primary" />
										</Button>
									</td>
								</tr>
							{/each}
						</tbody>
					</table>
				{:else}
					<div class="py-10 text-center text-muted-foreground">{m.invoice_selectors_port_selector_empty()}</div>
				{/if}
			</div>
		</div>

		<Dialog.Footer>
			{#if onClear}
				<Button variant="ghost" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
			{/if}
			<Button variant="outline" onclick={() => (open = false)}>{m.invoice_selectors_port_selector_cancel()}</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
