<script lang="ts">
	import { users } from "../data/store";
	import {
		getCoreRowModel,
		getPaginationRowModel,
		getFilteredRowModel,
		type ColumnDef,
		type PaginationState,
		type ColumnFiltersState,
	} from "@tanstack/table-core";
	import {
		createSvelteTable,
		renderComponent,
	} from "$lib/components/ui/data-table";
	import DataTable from "$lib/components/molecules/data-table/data-table.svelte";
	import DataTableActions from "$lib/components/molecules/data-table/data-table-actions.svelte";
	import Title from "$lib/components/atoms/title.svelte";
	import { goto } from "$app/navigation";
	import { adminSiteNavMap } from "$lib/core/constants";
	import { userVM } from "./user.vm.svelte";
	import { useDebounce } from "runed";
	import { capitalize } from "$lib/core/string.utils";

	// Define columns
	const columns: ColumnDef<any>[] = [
		{
			header: "Username",
			accessorKey: "username",
		},
		{
			header: "Email",
			accessorKey: "email",
			cell: ({ getValue }) => getValue<string>().toLowerCase(),
		},
		{
			header: "Discount",
			accessorKey: "discountPercent",
			cell: ({ getValue }) => {
				const val = getValue<number>();
				return val ? `${val}%` : "--.--%";
			},
		},
		{
			header: "Type",
			accessorKey: "role",
			cell: ({ getValue }) => capitalize(getValue<string>().toLowerCase()),
		},
		{
			header: "Action",
			id: "actions",
			cell: ({ row }) => {
				return renderComponent(DataTableActions, {
					actions: [
						{
							title: "View agent",
							action: () => {
								goto(
									`${adminSiteNavMap.users}/${row.original.id}`,
								);
							},
						},
					],
				});
			},
		},
	];

	let pagination = $state<PaginationState>({
		pageIndex: 0,
		pageSize: userVM.userInfo.limit,
	});
	let columnFilters = $state<ColumnFiltersState>([]);

	const table = createSvelteTable({
		get data() {
			return $users;
		},
		columns,
		getCoreRowModel: getCoreRowModel(),
		getPaginationRowModel: getPaginationRowModel(),
		getFilteredRowModel: getFilteredRowModel(),
		onPaginationChange: (updater) => {
			if (typeof updater === "function") {
				pagination = updater(pagination);
			} else {
				pagination = updater;
			}
		},
		onColumnFiltersChange: (updater) => {
			if (typeof updater === "function") {
				columnFilters = updater(columnFilters);
			} else {
				columnFilters = updater;
			}
		},
		state: {
			get pagination() {
				return pagination;
			},
			get columnFilters() {
				return columnFilters;
			},
		},
	});

	let debounceDuration = $state(1000);
	const debouncedSearch = useDebounce(
		() => {
			userVM.searchUsers();
		},
		() => debounceDuration,
	);
</script>

{#if $users.length > 0}
	<DataTable
		{table}
		onNextPageClick={() => {
			userVM.fetchNextPage();
		}}
		onPreviousPageClick={() => {
			userVM.fetchPrevPage();
		}}
		currPage={userVM.userInfo.page}
		totalPages={userVM.userInfo.totalPages}
		filterFieldDisabled={userVM.fetching}
		query={userVM.query}
		hasData={userVM.userInfo.data.length > 0}
		onQueryChange={(q) => {
			userVM.query = q;
			debouncedSearch();
		}}
		filterFieldPlaceholder="Search users..."
	/>
{:else}
	<div class="grid place-items-center p-4 py-12 md:p-8 md:py-24">
		<Title size="h5">No users found</Title>
	</div>
{/if}
