<script lang="ts">
	import Button, { buttonVariants } from '$lib/components/ui/button/button.svelte';
	import Input from '$lib/components/ui/input/input.svelte';
	import { SearchIcon, RefreshCcw } from '@lucide/svelte/icons';
	import Spinner from '$lib/components/ui/spinner/spinner.svelte';
	import * as Dialog from '$lib/components/ui/dialog/index';
	import Label from '$lib/components/ui/label/label.svelte';
	import * as Select from '$lib/components/ui/select/index';

	import DataTable from './data-table.svelte';
	import { columns, type RecipeOverview } from './columns';
	import { onDestroy, onMount } from 'svelte';
	import {
		currentRecipeVersionsSelector,
		recipeData,
		recipeFromServerQuery,
		recipeLoading,
		recipeOverviewData,
		recipeStreamMeta,
		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, getRecipeWithVersion } from '$lib/core/client/server.js';
	import { permission } from '$lib/core/stores/permissions';
	import type { RecipeVersion } from '$lib/models/recipe_version.model';

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

	let isRecipeLoading = $state(false);

	let version: string = $state('');
	let country: string = $state('');

	let value = $state('');
	let version_list: RecipeVersion[] = $state([]);

	const triggerVersion = $derived(
		version_list.find((f) => f.actual_version_name === value)?.display_version ?? version
	);

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

			let meta_snap = $state.snapshot(get(recipeStreamMeta));
			country = meta_snap?.country ?? '...';
			version = (meta_snap?.version ?? '...').split('_')[0];
		}
	});

	let unsubRecipeVersion = currentRecipeVersionsSelector.subscribe((vs) => {
		if (vs.length > 0) {
			version_list = vs;
		}
	});

	async function sendGetRecipeVersions(country: string) {
		version_list = [];
		await sendMessage({
			type: 'recipe_versions',
			payload: {
				auth: '',
				partial: false,
				country: country,
				version: -1,
				parameters: ''
			}
		});
	}

	function sendGetRecipeByVersionSelector() {
		getRecipeWithVersion(value);
	}

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

		await getRecipes();
	});

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

	$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);
			}
		}, 10000);

		version_list = get(currentRecipeVersionsSelector);

		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 [ {country} ] version [ {version} ]</h1>

				<div class="flex flex-row">
					<p class="mx-8 my-0 text-muted-foreground">
						Display menus from the current selected country
					</p>
					<!-- <Button variant="default" onclick={() => sendGetRecipeVersions(country)}>
						<span class="flex flex-row gap-2"> <RefreshCcw /> Change Version </span>
					</Button> -->

					<!-- dialog select version -->

					<Dialog.Root>
						<Dialog.Trigger
							type="button"
							class={buttonVariants({ variant: 'outline' })}
							onclick={() => sendGetRecipeVersions(country)}
						>
							<span class="flex flex-row gap-2"> <RefreshCcw /> Change Version </span>
						</Dialog.Trigger>

						<Dialog.Content class="sm:max-w-[425px]">
							<Dialog.Header>
								<Dialog.Title>Select Legacy Versions</Dialog.Title>
								<Dialog.Description>Viewing the previous version of recipe.</Dialog.Description>
							</Dialog.Header>
							<div class="grid gap-4">
								<!-- <div class="grid gap-3">
									<Label for="name-1">Version</Label>
									<Input id="name-1" name="name" defaultValue="Pedro Duarte" />
								</div> -->

								<Select.Root type="single" name="selectVersion" bind:value>
									<Select.Trigger class="w-[180px]">
										{triggerVersion}
									</Select.Trigger>

									<Select.Content>
										{#each version_list as version_n (version_n.actual_version_name)}
											<Select.Item
												value={version_n.actual_version_name}
												label={version_n.display_version}
											>
												{version_n.display_version}
											</Select.Item>
										{/each}
									</Select.Content>
								</Select.Root>
							</div>
							<Dialog.Footer>
								<Dialog.Close type="button" class={buttonVariants({ variant: 'outline' })}>
									Cancel
								</Dialog.Close>
								<Button type="submit" onclick={() => sendGetRecipeByVersionSelector()}>Ok</Button>
							</Dialog.Footer>
						</Dialog.Content>
					</Dialog.Root>
				</div>
			</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>
