<script lang="ts" generics="T extends Record<string, any>">
	import * as Table from "$lib/components/ui/table/index.js";
    import { Button } from "$lib/components/ui/button";
    import { goto } from "$app/navigation";
    import { page } from "$app/stores";

	type Column = {
		key: string;
		label: string;
		format?: (value: any, row: T) => string;
	};

	type SimpleDataTableProps<T> = {
		columns: Column[];
		data: T[];
        pageCount: number;
        totalItems: number;
	};

	let {
		data,
		columns,
        pageCount,
        totalItems
	}: SimpleDataTableProps<T> = $props();

    function handlePageChange(newPage: number) {
        const url = new URL($page.url);
        url.searchParams.set('page', newPage.toString());
        goto(url);
    }

	function getCellValue(row: T, column: Column): string {
		const value = row[column.key];
		if (column.format) {
			return column.format(value, row);
		}
		return value !== null && value !== undefined ? String(value) : '-';
	}
</script>

<div class="rounded-md border">
	<Table.Root>
		<Table.Header>
			<Table.Row inTabOrder={false}>
				{#each columns as column (column.key)}
					<Table.Head>{column.label}</Table.Head>
				{/each}
			</Table.Row>
		</Table.Header>
		<Table.Body>
			{#each data as row, i (i)}
				<Table.Row inTabOrder={false}>
					{#each columns as column (column.key)}
						<Table.Cell>
							{getCellValue(row, column)}
						</Table.Cell>
					{/each}
				</Table.Row>
			{:else}
				<Table.Row inTabOrder={false}>
					<Table.Cell colspan={columns.length} class="h-24 text-center">
						No hay resultados.
					</Table.Cell>
				</Table.Row>
			{/each}
		</Table.Body>
	</Table.Root>
</div>

<div class="flex items-center justify-end space-x-2 py-4">
    <div class="flex-1 text-sm text-muted-foreground">
        Total: {totalItems}
    </div>
    <div class="space-x-2">
        <Button
            variant="outline"
            size="sm"
            onclick={() => handlePageChange(Number($page.url.searchParams.get('page') || 1) - 1)}
            disabled={Number($page.url.searchParams.get('page') || 1) <= 1}
        >
            Anterior
        </Button>
        <Button
            variant="outline"
            size="sm"
            onclick={() => handlePageChange(Number($page.url.searchParams.get('page') || 1) + 1)}
            disabled={Number($page.url.searchParams.get('page') || 1) >= pageCount}
        >
            Siguiente
        </Button>
    </div>
</div>
