<script lang="ts">
	import * as Table from '$lib/components/ui/table';
	import { Button } from '$lib/components/ui/button';
	import { Plus, Pencil, Trash2, Inbox } from 'lucide-svelte';
	import { cn } from '$lib/utils';
	import { dodaFormT } from '$lib/i18n/doda-form-strings';

	interface Column {
		header: string;
		key: string;
		render?: (value: any) => string | any;
	}

	let {
		title = '',
		/** `en` / `es` (viene del padre; evita leer `page` aquí, más seguro con SSR) */
		locale: localeProp = 'es',
		columns = [],
		data = [],
		onAdd,
		onEdit,
		onDelete,
		/** Se dispara al elegir una fila (click / Enter). Útil p. ej. para precintos por contenedor. */
		onRowSelect,
		/** p. ej. `max-h-48` para limitar altura y scroll interno en tablas amplias */
		bodyMaxClass = '',
		class: className = ''
	}: {
		title?: string;
		locale?: 'en' | 'es';
		columns: Column[];
		data: any[];
		onAdd?: () => void;
		onEdit?: (item: any, index: number) => void;
		onDelete?: (item: any, index: number) => void;
		onRowSelect?: (item: any, index: number) => void;
		bodyMaxClass?: string;
		class?: string;
	} = $props();

	const dodaLoc = $derived((localeProp === 'en' ? 'en' : 'es') as 'en' | 'es');

	let selectedIndex = $state<number | null>(null);

	$effect(() => {
		if (data.length === 0) {
			selectedIndex = null;
		} else if (selectedIndex != null && selectedIndex >= data.length) {
			selectedIndex = data.length - 1;
		}
	});
</script>

<div
	class={cn(
		'space-y-0 overflow-hidden rounded-lg border border-border/60 bg-card/80 p-0 shadow-sm',
		className
	)}
>
	<div class="flex items-center border-b border-border/50 bg-muted/25 px-3 py-1.5">
		{#if title}
			<h3 class="text-xs font-medium text-muted-foreground">{title}</h3>
		{/if}
	</div>

	<div
		class={cn(
			'relative overflow-x-auto border-b border-border/40 bg-background/50',
			bodyMaxClass
		)}
	>
		<Table.Root>
			<Table.Header class="bg-muted/40">
				<Table.Row inTabOrder={false} class="hover:bg-transparent">
					{#each columns as col}
						<Table.Head
							class="h-7 px-2 py-1.5 text-left text-[0.65rem] font-medium uppercase leading-tight text-muted-foreground sm:px-3 sm:text-[0.7rem]"
						>
							{col.header}
						</Table.Head>
					{/each}
				</Table.Row>
			</Table.Header>
			<Table.Body>
				{#if data.length === 0}
					<Table.Row inTabOrder={false} class="hover:bg-transparent">
						<Table.Cell
							colspan={columns.length}
							class="h-16 py-2 text-center"
						>
							<div
								class="flex flex-col items-center justify-center gap-1 text-muted-foreground"
							>
								<Inbox class="h-5 w-5 opacity-45" />
								<span class="text-xs">{dodaFormT(dodaLoc, 'child_empty')}</span>
							</div>
						</Table.Cell>
					</Table.Row>
				{:else}
					{#each data as row, i}
						<Table.Row
							inTabOrder={false}
							role="button"
							tabindex="0"
							data-state={selectedIndex === i ? 'selected' : undefined}
							class="group transition-colors hover:bg-muted/30 {selectedIndex === i
								? 'bg-primary/5 ring-1 ring-inset ring-primary/25'
								: ''}"
							onclick={() => {
								selectedIndex = i;
								onRowSelect?.(row, i);
							}}
							onkeydown={(e) => {
								if (e.key === 'Enter' || e.key === ' ') {
									e.preventDefault();
									selectedIndex = i;
									onRowSelect?.(row, i);
								}
							}}
						>
							{#each columns as col}
								<Table.Cell
									class="max-w-[12rem] truncate px-2 py-1.5 text-xs sm:max-w-[14rem] sm:px-3 sm:text-sm"
								>
									{#if col.render}
										{col.render(row[col.key])}
									{:else}
										{row[col.key] ?? '-'}
									{/if}
								</Table.Cell>
							{/each}
						</Table.Row>
					{/each}
				{/if}
			</Table.Body>
		</Table.Root>
	</div>

	<div class="flex flex-wrap items-center justify-end gap-2 border-t border-border/30 bg-muted/20 px-3 py-2 sm:px-4">
		<Button variant="outline" size="sm" onclick={onAdd} class="h-8 gap-1.5 px-3 text-xs font-medium">
			<Plus class="h-3.5 w-3.5" />
			{dodaFormT(dodaLoc, 'child_new')}
		</Button>
		<Button
			variant="secondary"
			size="sm"
			onclick={() => {
				if (selectedIndex == null) return;
				const row = data[selectedIndex];
				if (row) onEdit?.(row, selectedIndex);
			}}
			class="h-8 gap-1 px-3 text-xs font-medium"
			disabled={data.length === 0 || selectedIndex == null}
		>
			<Pencil class="h-3.5 w-3.5" />
			{dodaFormT(dodaLoc, 'child_edit')}
		</Button>
		<Button
			variant="destructive"
			size="sm"
			onclick={() => {
				if (selectedIndex == null) return;
				const row = data[selectedIndex];
				if (row) onDelete?.(row, selectedIndex);
			}}
			class="h-8 gap-1 px-3 text-xs font-medium"
			disabled={data.length === 0 || selectedIndex == null}
		>
			<Trash2 class="h-3.5 w-3.5" />
			{dodaFormT(dodaLoc, 'child_delete')}
		</Button>
	</div>
</div>
