<script lang="ts">
	import { onMount } from 'svelte';
	import { Button } from '../ui/button';
	import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index';
	import { get } from 'svelte/store';
	import {
		materialFromServerQuery,
		materialFromMachineQuery,
		referenceFromPage
	} from '$lib/core/stores/recipeStore';
	import Input from '$lib/components/ui/input/input.svelte';

	import { SearchIcon, PlusIcon, BeanIcon, StarIcon } from '@lucide/svelte/icons';

	let { currentMat, onMatChange } = $props();
	let allMatData: any = $state();
	let refPage: string | undefined = $state();

	function changeMat(mat_id: string) {
		currentMat = mat_id;
		onMatChange(mat_id);
	}

	function getMaterialTypeIcon(mat_id: number) {}

	onMount(() => {
		refPage = get(referenceFromPage);
		if (refPage === 'brew') allMatData = get(materialFromMachineQuery);
		else if (refPage === 'overview') allMatData = get(materialFromServerQuery);

		// console.log('all mat data', JSON.stringify(allMatData));
	});
</script>

<DropdownMenu.Root>
	<DropdownMenu.Trigger>
		<Button variant="ghost" class="text-muted-foreground hover:bg-transparent">
			{currentMat}
		</Button>
	</DropdownMenu.Trigger>
	<DropdownMenu.Content>
		<div class="sticky top-0 z-10 my-4 flex items-center gap-2 bg-accent">
			<SearchIcon />
			<Input
				type="text"
				placeholder="Search by mat id or name"
				onchange={(e) => {}}
				oninput={(e) => {}}
			/>
		</div>

		<!-- permission create mat -->
		<DropdownMenu.Item>
			<div class="flex gap-2">
				<PlusIcon />
				<p>Create Material</p>
			</div>
		</DropdownMenu.Item>

		{#each allMatData as mat}
			<DropdownMenu.Item onclick={() => changeMat(`${mat.materialOtherName} (${mat.id})`)}>
				<div class="flex gap-2">
					{#if mat.BeanChannel}
						<BeanIcon />
					{:else if mat.id > 8110 && mat.id < 8131}
						<StarIcon />
					{/if}

					<p>{mat.materialOtherName} ({mat.id})</p>
				</div>
			</DropdownMenu.Item>
		{:else}
			<DropdownMenu.Item>
				<p class="text-muted-foreground">No materials available</p>
			</DropdownMenu.Item>
		{/each}
	</DropdownMenu.Content>
</DropdownMenu.Root>
