<script>
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import { browser } from '$app/environment';
	const save_icon = '/assets/save_icon.svg';
	const trash_icon = '/assets/trash_white.svg';
	const arrow_back = '/assets/arrow_back.svg';
	const add_green = '/assets/add_green.svg';
	const cart_icon = '/assets/cart_icon.svg';

	const API = (import.meta.env.VITE_API_URL || '').replace(/\/+$/, '');

	let token = null;
	let company = null;
	let orderId = null;
	let tableIdNum = null;
	let tableName = null;
	let kitchenNote = '';
	let showKitchenNoteModal = false;
	let selectedProduct = [];

	if (browser) {
		token = localStorage.getItem('token');
		company = Number(localStorage.getItem('company'));
		orderId = Number(localStorage.getItem('order'));
		tableIdNum = localStorage.getItem('table');
		localStorage.setItem('typePage', 'false');
		tableName = localStorage.getItem('tableName');
	}

	let selectedCategory = null;

	let localOrderItems = [];
	let products = [];
	let categories = [];

	if (browser) {
		const storedItems = localStorage.getItem(`orderItems_${orderId}`);
		if (storedItems) {
			localOrderItems = JSON.parse(storedItems);
		}
	}

	$: totalAmount = localOrderItems.reduce(
		(sum, item) => sum + Number(item.product_details?.product_price ?? 0) * (item.quantity ?? 1),
		0
	);

	$: if (browser && localOrderItems) {
		localStorage.setItem(`orderItems_${orderId}`, JSON.stringify(localOrderItems));
	}

	async function fetchProductsAndCategories() {
		try {
			const myHeaders = new Headers();
			myHeaders.append('Authorization', `Bearer ${token}`);
			myHeaders.append('Content-Type', 'application/json');

			const raw = JSON.stringify({
				company_id: company
			});

			const requestOptions = {
				method: 'POST',
				headers: myHeaders,
				body: raw,
				redirect: 'follow'
			};

			const resCategories = await fetch(
				`${API}/category/get`,
				requestOptions
			);
			const categoriesResult = await resCategories.json();
			categories = categoriesResult.data || [];

			const resProducts = await fetch(
				`${API}/product/get`,
				requestOptions
			);
			const productsResult = await resProducts.json();
			products = productsResult.data || [];
		} catch (error) {
			console.error('Erro ao buscar produtos e categorias:', error);
		}
	}

	onMount(async () => {
		await fetchProductsAndCategories();
	});

	$: if (categories.length > 0 && !selectedCategory) {
		selectedCategory = categories[0].category_name;
	}

	$: filteredProducts = selectedCategory
		? products.filter((p) => {
				const cat = categories.find((c) => c.category_id === p.category_id);
				return cat?.category_name === selectedCategory;
			})
		: products;

	function handleAddItem(product) {
		if (product.product_is_kitchen) {
			selectedProduct = product;
			showKitchenNoteModal = true;
			return;
		}

		addItemToOrder(product, null);
	}

	function confirmKitchenNote() {
		addItemToOrder(selectedProduct, kitchenNote);
		showKitchenNoteModal = false;
		kitchenNote = '';
		selectedProduct = null;
	}

	function addItemToOrder(product, note) {
		if (product.product_is_kitchen) {
			const newItem = {
				order_item_id: Date.now(),
				product_details: product,
				quantity: 1,
				kitchen_note: note
			};
			localOrderItems = [...localOrderItems, newItem];
		} else {
			const newItem = {
				order_item_id: Date.now(),
				product_details: product,
				quantity: 1,
				kitchen_note: note
			};
			localOrderItems = [...localOrderItems, newItem];
		}
	}

	function removeItemFromOrder(itemId) {
		localOrderItems = localOrderItems.filter((item) => item.order_item_id !== itemId); // Update localOrderItems
	}

	async function handleSendToKitchen() {
		//console.log(token, company, orderId);
		if (localOrderItems.length === 0) return;

		const myHeaders = new Headers();
		myHeaders.append('Authorization', `Bearer ${token}`);
		myHeaders.append('Content-Type', 'application/json');

		try {
			let success = true;
			for (const item of localOrderItems) {
				//console.log(item.product_details.product_id);
				const payload = {
					company_id: company,
					order_id: orderId,
					product_id: item.product_details.product_id,
					kitchen_note: item.kitchen_note
				};
				const response = await fetch(`${API}/order_item/create`, {
					method: 'POST',
					headers: myHeaders,
					body: JSON.stringify(payload)
				});
				if (response.status == '401') {
					console.log('ativa o popup');
				}
				if (!response.ok) {
					success = false;
					console.error('Erro ao enviar item para cozinha:', response.statusText);
					break;
				}
			}
			if (success) {
				localOrderItems = [];
				if (browser) {
					localStorage.removeItem(`orderItems_${orderId}`);
				}
			}
		} catch (error) {
			console.error('Erro ao enviar para cozinha:', error);
		}
	}
</script>

<div class="container mx-auto">
	<div class="mb-6 flex items-center">
		<button
			on:click={() => goto('/dashboard/commands')}
			class="mr-4 rounded-lg bg-gray-800 p-2 hover:bg-gray-700"
		>
			<img src={arrow_back} alt="Voltar" class="h-5 w-5" />
		</button>
		<h1 class="text-2xl font-bold">Mesa {tableName}</h1>
	</div>

	<div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
		<div class="overflow-hidden rounded-lg bg-gray-800 shadow-lg lg:col-span-2">
			<div class="bg-gray-700 p-4">
				<h2 class="text-lg font-semibold">Adicionar Produtos</h2>
			</div>

			<div class="bg-gray-750 flex overflow-x-auto border-b border-gray-700 p-2">
				{#each categories as category}
					<button
						class="mx-1 whitespace-nowrap rounded-md px-4 py-2 text-sm font-medium {selectedCategory ===
						category.category_name
							? 'bg-indigo-600 text-white'
							: 'bg-gray-700 text-gray-300 hover:bg-gray-600'}"
						on:click={() => (selectedCategory = category.category_name)}
					>
						{category.category_name}
					</button>
				{/each}
			</div>

			<div
				class="grid max-h-[calc(100vh-400px)] grid-cols-2 gap-4 overflow-y-auto p-4 sm:grid-cols-3 md:grid-cols-4"
			>
				{#each filteredProducts as product}
					<button
						class="hover:bg-gray-650 rounded-lg bg-gray-700 p-4 text-left"
						on:click={() => handleAddItem(product)}
					>
						<div class="flex h-full flex-col">
							<h3 class="mb-2 line-clamp-2 font-medium">
								{product.product_name ?? 'Nome Indisponível'}
							</h3>
							<div class="mt-auto flex items-center justify-between">
								<span class="font-semibold text-emerald-400"
									>R$ {Number(product.product_price ?? 0).toFixed(2)}</span
								>
								<img src={add_green} alt="Adicionar" class="h-5 w-5 text-emerald-400" />
							</div>
							{#if product.product_is_kitchen}
								<span class="mt-2 rounded-full bg-yellow-800 px-2 py-0.5 text-xs text-yellow-300"
									>Cozinha</span
								>
							{/if}
						</div>
					</button>
				{/each}
			</div>
		</div>

		<div
			class="flex h-full flex-col overflow-hidden rounded-lg bg-gray-800 shadow-lg md:h-[calc(100vh-200px)]"
		>
			<div class="bg-gray-700 p-4">
				<h2 class="text-lg font-semibold">Comanda</h2>
			</div>

			<div class="flex-1 overflow-y-auto p-4">
				{#if localOrderItems.length === 0}
					<div class="py-6 text-center text-gray-400">
						<img src={cart_icon} class="mx-auto mb-2 h-10 w-10 opacity-50" alt="Nenhum item" />
						<p>Nenhum item adicionado</p>
					</div>
				{:else}
					{#each localOrderItems as item, index}
						<div class="bg-gray-750 flex items-center justify-between rounded-lg p-3">
							<div class="flex-1">
								<h3 class="font-medium">
									{item.product_details?.product_name ?? 'Nome Indisponível'}
								</h3>
								<p class="text-sm text-gray-400">
									R$ {Number(item.product_details?.product_price ?? 0).toFixed(2)} x {item.quantity ??
										1}
								</p>
							</div>
							<div class="flex items-center space-x-2">
								<button
									on:click={() => removeItemFromOrder(item.order_item_id)}
									class="ml-2 rounded bg-red-700 p-1 hover:bg-red-600"
								>
									<img src={trash_icon} class="h-4 w-4" alt="Remover" />
								</button>
							</div>
						</div>
					{/each}
				{/if}
			</div>

			<div class="bg-gray-750 border-t border-gray-700 p-4">
				<div class="mb-2 flex justify-between">
					<span class="font-medium">Subtotal:</span>
					<span>R$ {totalAmount.toFixed(2)}</span>
				</div>

				<button
					on:click={handleSendToKitchen}
					disabled={localOrderItems.length === 0}
					class="flex w-full items-center justify-center rounded-lg bg-emerald-600 py-3 font-medium hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-50"
				>
					Enviar para Cozinha
				</button>
			</div>
		</div>
	</div>
	{#if showKitchenNoteModal}
		<div class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
			<div class="w-full max-w-md rounded-lg bg-gray-800 p-6 shadow-lg">
				<h2 class="mb-4 text-lg font-semibold">Anotações para o produto</h2>
				<form on:submit={confirmKitchenNote} class="space-y-4">
					<div>
						<p class="mb-1 block text-sm text-gray-400">Anotações</p>
						<input
							bind:value={kitchenNote}
							placeholder="Detalhes do pedido"
							class="w-full rounded-md border border-gray-600 bg-gray-700 px-3 py-2 focus:ring-emerald-500"
						/>
					</div>
					<div class="flex space-x-2">
						<button
							type="button"
							on:click={() => ((showKitchenNoteModal = false), (kitchenNote = ''))}
							class="rounded-lg bg-gray-700 px-4 py-2 hover:bg-gray-600"
						>
							Cancelar
						</button>
						<button
							type="submit"
							class="flex items-center rounded-lg bg-emerald-600 px-4 py-2 hover:bg-emerald-700"
						>
							<img src={save_icon} alt="Salvar" class="mr-2 h-4 w-4" /> Salvar
						</button>
					</div>
				</form>
			</div>
		</div>
	{/if}
</div>
