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

	let { data }: { data: FullOrderModel[] } = $props();

	// Define columns
	const columns: ColumnDef<any>[] = [
		{
			header: "#",
			accessorKey: "id",
			cell: ({ row }) => {
				return Number(row.id) + 1;
			},
		},
		{
			header: "Product",
			accessorKey: "product",
			cell: ({ row }) => {
				const r = row.original as FullOrderModel;
				return r.product.title;
			},
		},
		{
			header: "Customer",
			accessorKey: "customer",
			cell: ({ row }) => {
				const r = row.original as FullOrderModel;
				if (!r.customerInfo) return "N/A";
				return `${r.customerInfo.firstName} ${r.customerInfo.lastName}`;
			},
		},
		{
			header: "Customer Email",
			accessorKey: "customerEmail",
			cell: ({ row }) => {
				const r = row.original as FullOrderModel;
				return r.customerInfo?.email || "N/A";
			},
		},
		{
			header: "Price",
			accessorKey: "orderPrice",
			cell: ({ row }) => {
				const r = row.original as FullOrderModel;
				return `$${r.orderPrice.toFixed(2)}`;
			},
		},
		{
			header: "Status",
			accessorKey: "status",
			cell: ({ row }) => {
				const r = row.original as FullOrderModel;
				return snakeToSpacedPascal(r.status.toLowerCase());
			},
		},
		{
			header: "Action",
			id: "actions",
			cell: ({ row }) => {
				return renderComponent(DataTableActions, {
					actions: [
						{
							title: "View Order",
							action: () => {
								goto(
									`${adminBasePath}/orders/${row.original.id}`,
								);
							},
						},
					],
				});
			},
		},
	];

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

	const table = createSvelteTable({
		get data() {
			return data;
		},
		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(
		() => {
			console.log("Debounced search - NYI");
		},
		() => debounceDuration,
	);

	let pageCount = $derived(Math.ceil(data.length / pagination.pageSize) || 1);
</script>

{#if data.length > 0}
	<DataTable
		{table}
		onNextPageClick={() => {
			table.nextPage();
		}}
		onPreviousPageClick={() => {
			table.previousPage();
		}}
		currPage={pagination.pageIndex + 1}
		totalPages={pageCount}
		filterFieldDisabled={false}
		query={orderVM.query}
		hasData={data.length > 0}
		onQueryChange={(q) => {
			orderVM.query = q;
			debouncedSearch();
		}}
		filterFieldPlaceholder="Search orders..."
	/>
{:else}
	<div class="grid h-full place-items-center p-4 py-12 md:p-8 md:py-32">
		<Title size="h5">No Orders found</Title>
	</div>
{/if}
