<script lang="ts">
	import type { Table as TableType } from "@tanstack/table-core";

	import * as Table from "$lib/components/ui/table/index.js";
	import { Button } from "$lib/components/ui/button/index.js";
	import { Input } from "$lib/components/ui/input/index.js";
	import Title from "$lib/components/atoms/title.svelte";
	import { FlexRender } from "$lib/components/ui/data-table";

	let {
		table,
		query = "",
		hasData,
		currPage,
		totalPages,
		filterFieldPlaceholder,
		onPreviousPageClick,
		onNextPageClick,
		onQueryChange,
		filterFieldDisabled = false,
	}: {
		table: TableType<any>;
		query: string;
		hasData: boolean;
		currPage: number;
		totalPages: number;
		filterFieldDisabled?: boolean;
		filterFieldPlaceholder?: string;
		onQueryChange?: (q: string) => void;
		onPreviousPageClick?: () => void;
		onNextPageClick?: () => void;
	} = $props();

	function gotoPreviousPage() {
		onPreviousPageClick && onPreviousPageClick();
	}

	function gotoNextPage() {
		onNextPageClick && onNextPageClick();
	}
</script>

<div class="h-full w-full">
	<div class="mb-4 flex flex-col items-center gap-4 sm:flex-row">
		<Input
			class="w-full md:max-w-xs"
			placeholder={filterFieldPlaceholder ?? "Search..."}
			type="text"
			disabled={filterFieldDisabled}
			bind:value={query}
			oninput={(e) => {
				onQueryChange && onQueryChange(e.currentTarget.value);
			}}
		/>
	</div>

	{#if hasData}
		<Table.Root class="w-full min-w-[40rem]">
			<Table.Header>
				{#each table.getHeaderGroups() as headerGroup}
					<Table.Row>
						{#each headerGroup.headers as header}
							<Table.Head>
								{#if !header.isPlaceholder}
									<FlexRender
										content={header.column.columnDef.header}
										context={header.getContext()}
									/>
								{/if}
							</Table.Head>
						{/each}
					</Table.Row>
				{/each}
			</Table.Header>
			<Table.Body>
				{#each table.getRowModel().rows as row}
					<Table.Row>
						{#each row.getVisibleCells() as cell}
							<Table.Cell>
								<FlexRender
									content={cell.column.columnDef.cell}
									context={cell.getContext()}
								/>
							</Table.Cell>
						{/each}
					</Table.Row>
				{/each}
			</Table.Body>
		</Table.Root>

		<div class="flex items-center justify-end space-x-2 py-4">
			<div class="flex-1 text-sm text-muted-foreground">
				Showing page {currPage} of {totalPages}
			</div>
			<Button
				variant="outline"
				size="sm"
				onclick={gotoPreviousPage}
				disabled={currPage <= 1}>Previous</Button
			>
			<Button
				variant="outline"
				size="sm"
				disabled={currPage >= totalPages}
				onclick={gotoNextPage}>Next</Button
			>
		</div>
	{:else}
		<div class="grid w-full place-items-center p-4 py-32 md:p-8 md:py-64">
			<Title size="h5">No data found</Title>
		</div>
	{/if}
</div>
