<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import * as Table from '$lib/components/ui/table';
	import { Badge } from '$lib/components/ui/badge';
	import { Plus, Minus, Search, Loader2, Ghost } from 'lucide-svelte';
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';
	import { fly } from 'svelte/transition';
	import { getInvoiceTypeColor } from '$lib/utils';

	let {
		title = '',
		invoices = [] as Invoice[],
		loading = false,
		isAdding = false, // True if this table is for "Available" invoices (to add)
		readOnly = false,
		onAction = (invoice: Invoice) => {}
	} = $props();

	let searchTerm = $state('');

	// Filtro local simple
	const filteredInvoices = $derived(
		invoices.filter((inv) => {
			if (!searchTerm) return true;
			const term = searchTerm.toLowerCase();
			return (
				inv.invoice_number?.toLowerCase().includes(term) ||
				inv.invoice_type?.toLowerCase().includes(term)
			);
		})
	);
</script>

<div class="space-y-4">
	<div class="flex items-center justify-between">
		<h3 class="text-sm font-semibold text-muted-foreground uppercase">
			{title}
			<Badge variant="secondary" class="ml-2">{filteredInvoices.length}</Badge>
		</h3>
		<div class="relative w-48">
			<Search class="absolute top-2.5 left-2 h-4 w-4 text-muted-foreground" />
			<Input placeholder="Buscar..." class="h-9 pl-8" bind:value={searchTerm} />
		</div>
	</div>

	<div class="relative h-[300px] overflow-auto rounded-md border">
		<Table.Root>
			<Table.Header class="sticky top-0 z-10 bg-background">
				<Table.Row>
					<Table.Head>Factura Expo</Table.Head>
					<Table.Head>Fecha</Table.Head>
					<Table.Head>P. Neto</Table.Head>
					<Table.Head>P. Bruto</Table.Head>
					<Table.Head>Bultos</Table.Head>
					<Table.Head>Valor (USD)</Table.Head>
					<Table.Head>Tipo</Table.Head>
					<Table.Head class="w-[50px]"></Table.Head>
				</Table.Row>
			</Table.Header>
			<Table.Body>
				{#if loading}
					<Table.Row>
						<Table.Cell colspan={8} class="h-24 text-center">
							<div class="flex items-center justify-center gap-2">
								<Loader2 class="h-4 w-4 animate-spin" />
								<span>Cargando...</span>
							</div>
						</Table.Cell>
					</Table.Row>
				{:else if filteredInvoices.length === 0}
					<Table.Row>
						<Table.Cell colspan={8} class="h-32 text-center text-muted-foreground">
							<div class="flex flex-col items-center justify-center gap-2">
								<Ghost class="h-8 w-8 opacity-20" />
								<span>No hay facturas disponibles</span>
							</div>
						</Table.Cell>
					</Table.Row>
				{:else}
					{#each filteredInvoices as invoice (invoice.id)}
						<tr
							class="border-b transition-colors data-[state=selected]:bg-muted {invoice.is_selected
								? 'bg-primary/5'
								: ''} {readOnly ? '' : 'cursor-pointer hover:bg-muted/50 hover:bg-primary/10'}"
							onclick={() => !readOnly && onAction(invoice)}
							in:fly={{ y: 20, duration: 300 }}
							out:fly={{ x: isAdding ? 20 : -20, duration: 200 }}
						>
							<Table.Cell class="font-mono text-xs font-medium">
								<span class={invoice.is_selected ? 'font-bold text-primary' : ''}
									>{invoice.invoice_number}</span
								>
							</Table.Cell>
							<Table.Cell class="text-xs">{invoice.invoice_date}</Table.Cell>
							<Table.Cell class="text-xs">{invoice.financials?.net_weight ?? '-'}</Table.Cell>
							<Table.Cell class="text-xs">{invoice.financials?.gross_weight ?? '-'}</Table.Cell>
							<Table.Cell class="text-xs">{invoice.financials?.bundle_count ?? '-'}</Table.Cell>
							<Table.Cell class="text-xs font-medium text-green-600">
								{new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(
									Number(invoice.financials?.value_me ?? 0)
								)}
							</Table.Cell>
							<Table.Cell class="text-xs"
								><Badge variant="outline" class={getInvoiceTypeColor(invoice.invoice_type)}
									>{invoice.invoice_type}</Badge
								></Table.Cell
							>
							<Table.Cell>
								<!-- Visual Indicator Only -->
								<div class="flex items-center justify-center">
									<div
										class="h-4 w-4 rounded-full border border-primary {invoice.is_selected
											? 'bg-primary'
											: 'bg-transparent'} transition-colors"
									></div>
								</div>
							</Table.Cell>
						</tr>
					{/each}
				{/if}
			</Table.Body>
		</Table.Root>
	</div>
</div>
