<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, Loader2 } from 'lucide-svelte';
	import { manifestApi, type Manifest } from '$lib/api/dashboard/a76/manifests';
	import { companyStore } from '$lib/stores/company.svelte';
	import { m } from '$lib/i18n/messages';
	import { toast } from 'svelte-sonner';

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

	let manifests = $state<Manifest[]>([]);
	let loading = $state(false);
	let searchTerm = $state('');

	async function searchManifests() {
		if (!companyStore.activeCompany) return;
		loading = true;
		try {
			const res = await manifestApi.list(companyStore.activeCompany.id, {
				manifest_number: searchTerm
			});
			if (res.data) {
				manifests = res.data.items || [];
			}
		} catch (e) {
			console.error('Error searching manifests:', e);
			toast.error(m.invoice_selectors_manifest_selector_search_button());
		} finally {
			loading = false;
		}
	}

	function handleSelect(manifest: Manifest) {
		onSelect(manifest);
		open = false;
	}

	$effect(() => {
		if (open) {
			searchManifests();
		}
	});
</script>

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

		<div class="space-y-4 py-4">
			<div class="flex gap-2">
				<div class="relative flex-1">
					<Search class="absolute top-2.5 left-2.5 h-4 w-4 text-muted-foreground" />
					<Input
						placeholder={m.invoice_selectors_manifest_selector_search_placeholder()}
						class="h-9 pl-8"
						bind:value={searchTerm}
						onkeydown={(e) => e.key === 'Enter' && searchManifests()}
					/>
				</div>
				<Button size="sm" onclick={searchManifests} disabled={loading}>
					{#if loading}
						<Loader2 class="mr-2 h-4 w-4 animate-spin" />
					{/if}
					{m.invoice_selectors_manifest_selector_search_button()}
				</Button>
			</div>

			<div class="max-h-[400px] overflow-y-auto rounded-md border text-xs">
				<table class="w-full">
					<thead class="sticky top-0 bg-muted/90 text-left backdrop-blur-sm">
						<tr>
							<th class="p-3 font-semibold tracking-wider text-muted-foreground uppercase"
								>{m.invoice_selectors_manifest_selector_column_number()}</th
							>
							<th class="p-3 font-semibold tracking-wider text-muted-foreground uppercase"
								>{m.invoice_selectors_manifest_selector_column_description()}</th
							>
						</tr>
					</thead>
					<tbody class="divide-y">
						{#if manifests.length === 0}
							<tr>
								<td colspan="2" class="p-12 text-center text-muted-foreground">
									{#if loading}
										{m.invoice_selectors_manifest_selector_searching()}
									{:else}
										{m.invoice_selectors_manifest_selector_empty()}
									{/if}
								</td>
							</tr>
						{:else}
							{#each manifests as manifest}
								<tr
									class="group cursor-pointer transition-colors hover:bg-muted/50"
									onclick={() => handleSelect(manifest)}
								>
									<td
										class="p-3 font-mono font-bold text-primary transition-colors group-hover:text-primary/80"
									>
										{manifest.manifest_number}
									</td>
									<td
										class="max-w-[400px] truncate p-3 text-muted-foreground italic"
										title={manifest.description}
									>
										{manifest.description || '-'}
									</td>
								</tr>
							{/each}
						{/if}
					</tbody>
				</table>
			</div>
		</div>
		<div class="flex shrink-0 items-center justify-end gap-2 border-t px-6 py-3">
			{#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>
