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

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

	let {
		title = '',
		columns = [],
		data = [],
		onAdd,
		onEdit,
		onDelete,
		class: className = ''
	}: {
		title?: string;
		columns: Column[];
		data: any[];
		onAdd?: () => void;
		onEdit?: (item: any, index: number) => void;
		onDelete?: (item: any, index: number) => void;
		class?: string;
	} = $props();
</script>

<div class={cn('space-y-4 rounded-xl border bg-card p-4 shadow-sm', className)}>
	<div class="flex items-center justify-between">
		{#if title}
			<h3 class="text-sm font-semibold tracking-wider text-muted-foreground uppercase">{title}</h3>
		{/if}
	</div>

	<div class="relative overflow-hidden rounded-md border bg-background">
		<Table.Root>
			<Table.Header class="bg-muted/50">
				<Table.Row>
					{#each columns as col}
						<Table.Head class="h-10 px-4 text-xs font-semibold whitespace-nowrap"
							>{col.header}</Table.Head
						>
					{/each}
				</Table.Row>
			</Table.Header>
			<Table.Body>
				{#if data.length === 0}
					<Table.Row>
						<Table.Cell
							colspan={columns.length}
							class="h-24 text-center text-sm text-muted-foreground"
						>
							No hay registros.
						</Table.Cell>
					</Table.Row>
				{:else}
					{#each data as row, i}
						<Table.Row class="group transition-colors hover:bg-muted/30">
							{#each columns as col}
								<Table.Cell class="px-4 py-2 text-sm whitespace-nowrap">
									{#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 justify-end gap-2 pt-2">
		<Button variant="outline" size="sm" onclick={onAdd} class="h-8 gap-1 px-3 text-xs font-medium">
			<Plus class="h-3.5 w-3.5" />
			Nuevo
		</Button>
		<Button
			variant="secondary"
			size="sm"
			onclick={() => {}}
			class="h-8 gap-1 px-3 text-xs font-medium"
			disabled={data.length === 0}
		>
			<Pencil class="h-3.5 w-3.5" />
			Editar
		</Button>
		<Button
			variant="destructive"
			size="sm"
			onclick={() => {}}
			class="h-8 gap-1 px-3 text-xs font-medium"
			disabled={data.length === 0}
		>
			<Trash2 class="h-3.5 w-3.5" />
			Borrar
		</Button>
	</div>
</div>
