<script lang="ts">
	import Button from '$lib/components/ui/button/button.svelte';
	import Input from '$lib/components/ui/input/input.svelte';
	import { SearchIcon } from '@lucide/svelte/icons';
	import Spinner from '$lib/components/ui/spinner/spinner.svelte';

	import DataTable from './data-table.svelte';
	import { columns, type RecipeOverview } from './columns';
	import { onDestroy, onMount } from 'svelte';
	import {
		loadRecipe,
		recipeData,
		recipeFromServerQuery,
		recipeLoading,
		recipeOverviewData,
		referenceFromPage
	} from '$lib/core/stores/recipeStore.js';
	import { sendMessage } from '$lib/core/handlers/ws_messageSender.js';
	import { auth } from '$lib/core/stores/auth.js';
	import { get } from 'svelte/store';
	import { getRecipes } from '$lib/core/client/server.js';
	import { permission } from '$lib/core/stores/permissions';

	let data: { recipes: RecipeOverview[] } = $state({
		recipes: []
	});

	let isRecipeLoading = $state(false);

	let unsubRecipeData = recipeOverviewData.subscribe((rd) => {
		if (rd) {
			data.recipes = rd == null ? [] : rd;
		}
	});

	onMount(async () => {
		// do load recipe
		// loadRecipe();
		referenceFromPage.set('overview');

		await getRecipes();
	});

	onDestroy(() => {
		unsubRecipeData();
	});

	$effect(() => {
		const recipeFetchInterval = setInterval(async () => {
			// schedule check if recipe is empty
			if (data.recipes.length == 0) {
				console.log('loading recipe ....');
				// recipeLoading.set(true);
				// empty
				await getRecipes();

				// setTimeout(() => recipeLoading.set(false), 3000);
			}
		}, 30000);
		return () => {
			clearInterval(recipeFetchInterval);
		};
	});
</script>

<div class="mx-8 flex">
	<!-- header -->
	<div class="w-full">
		<div class="mb-4 flex items-center justify-between">
			<div>
				<h1 class="m-8 text-4xl font-bold">Overview</h1>
				<p class="mx-8 my-0 text-muted-foreground">
					Display menus from the current selected country
				</p>
			</div>
			<div class="mx-8 my-4 flex gap-2">
				<Button variant="default">+ Create Menu</Button>
			</div>
		</div>
		<!-- search bar -->
		<!-- <div class="mx-4 my-8 flex w-full items-center justify-center gap-2">
			<SearchIcon />
			<Input type="text" placeholder="Search by id, product code, name or material" class="" />
		</div> -->
		<!-- filter -->

		<!-- table -->

		<div class="w-full overflow-auto">
			{#if $recipeLoading}
				<div class="flex items-center justify-center">
					<p class="mx-4">Please wait</p>
					<Spinner />
				</div>
			{:else}
				<DataTable data={data.recipes} refPage="overview" {columns} />
			{/if}
		</div>
	</div>
</div>
