<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 {
		getCoreRowModel,
		getFilteredRowModel,
		getPaginationRowModel,
		type ColumnDef,
		type ColumnFiltersState,
		type PaginationState,
	} from "@tanstack/table-core";
	import { useDebounce } from "runed";
	import { OrderStatus } from "../data/entities";
	import { orderVM } from "./order.vm.svelte";

	function getStatusVariant(status: OrderStatus) {
		switch (status) {
			case OrderStatus.FULFILLED:
				return "success";
			case OrderStatus.PARTIALLY_FULFILLED:
				return "default";
			case OrderStatus.PENDING_FULFILLMENT:
				return "secondary";
			case OrderStatus.CANCELLED:
				return "destructive";
			default:
				return "outline";
		}
	}

	function formatStatus(status: OrderStatus): string {
		return status
			.split("_")
			.map((word) => word.charAt(0) + word.slice(1).toLowerCase())
			.join(" ");
	}

	// Define columns
	const columns: ColumnDef<any>[] = [
		{
			header: "Order ID",
			accessorKey: "id",
			cell: ({ row }) => `#${row.original.id}`,
		},
		{
			header: "Product",
			id: "product",
			cell: ({ row }) => {
				return row.original.product.title;
			},
		},
		{
			header: "Price",
			id: "price",
			cell: ({ row }) => {
				const basePrice = row.original.displayPrice;
				const finalPrice = row.original.basePrice;
				const hasDiscount = row.original.discountAmount > 0;

				return hasDiscount
					? `$${finalPrice.toFixed(2)} (was $${basePrice.toFixed(2)})`
					: `$${finalPrice.toFixed(2)}`;
			},
		},
		{
			header: "Status",
			accessorKey: "status",
			cell: ({ row }) => {
				return formatStatus(row.original.status);
			},
		},
		{
			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: orderVM.orderInfo.limit,
	});
	let columnFilters = $state<ColumnFiltersState>([]);

	const table = createSvelteTable({
		get data() {
			return orderVM.orderInfo.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(
		() => {
			orderVM.searchOrders();
		},
		() => debounceDuration,
	);
</script>

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