<script>
	import { onMount } from 'svelte';
	import OrderCard from '$lib/component/OrderCard.svelte';
	import HistoricModal from '$lib/component/HistoricModal.svelte';
	import { browser } from '$app/environment';
	import { typePage } from '$lib/utils/store';

	let pedidosAtivos = [];
	let pedidosConcluidos = [];
	let company = null;
	let token = null;
	let mostrarHistorico = false;
	let oldData = 0;
	let hostname = '';

	if (browser) {
		token = localStorage.getItem('token');
		company = Number(localStorage.getItem('company'));
		hostname = window.location.pathname;
		localStorage.setItem('typePage', hostname);
	}

	const abrirHistorico = () => (mostrarHistorico = true);
	const fecharHistorico = () => (mostrarHistorico = false);

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

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

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

			const resp = await fetch('https://bartender.mixtab.com.br/order_item/update', requestOptions);
			const data = await resp.text();

			await fetchItems();
		} catch (err) {
			console.error('Erro ao atualizar item:', err);
		}
	}

	async function fetchItems() {
		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 response = await fetch('https://bartender.mixtab.com.br/kitchen/get', requestOptions);
			if (!response.ok) {
				console.error('Erro na resposta do servidor:', response.status, response.statusText);
				return;
			}
			const ordersResult = await response.json();
			console.log(ordersResult);
			const totalItems = (ordersResult.data || []).reduce((acc, pedido) => {
				return acc + (pedido.items ? pedido.items.length : 0);
			}, 0);
			console.log(localStorage.getItem('typePage'));
			if (totalItems > oldData && localStorage.getItem('typePage') == '/dashboard/kitchen') {
				const audio = new Audio('/som.mp3');
				audio.play().catch((e) => console.warn('Erro ao tocar som:', e));
			}
			oldData = totalItems;

			pedidosAtivos = [];
			pedidosConcluidos = [];

			(ordersResult.data || []).forEach((p) => {
				const itensAndamento = p.items
					.filter((i) => i.order_item_flag === 'a')
					.map((i) => ({
						id: i.order_item_id,
						nome: i.product_name,
						comanda_nome: i.order_name,
						observacao: i.kitchen_note?.trim() || null
					}));

				const itensProntos = p.items
					.filter((i) => i.order_item_flag === 'p')
					.map((i) => ({
						id: i.order_item_id,
						nome: i.product_name,
						comanda_nome: i.order_name,
						observacao: i.kitchen_note?.trim() || null
					}));

				if (itensAndamento.length > 0) {
					pedidosAtivos.push({
						id: p.order_id,
						mesa: p.table_number,
						user_name: p.user_name,
						comanda_nome: p.order_name,
						items: itensAndamento
					});
				}

				if (itensProntos.length > 0) {
					pedidosConcluidos.push({
						id: p.order_id,
						mesa: p.table_number,
						user_name: p.user_name,
						comanda_nome: p.order_name,
						items: itensProntos
					});
				}
			});
		} catch (error) {
			console.error('Erro ao carregar pedidos:', error);
		}
	}

	onMount(() => {
		fetchItems();
		setInterval(fetchItems, 5000);
	});
</script>

<main class="relative rounded-xl bg-gray-800 p-6 text-white shadow-lg">
	<h1 class="mb-6 text-3xl font-bold">Cozinha ao vivo</h1>

	<div class="absolute right-6 top-6">
		<button
			class="h-12 w-40 rounded-lg bg-yellow-400 font-semibold text-black shadow-md transition-colors duration-200 hover:bg-yellow-300"
			on:click={abrirHistorico}
		>
			Ver histórico
		</button>
	</div>

	<div class="mt-20 space-y-6">
		{#each pedidosAtivos as pedido (pedido.id)}
			<OrderCard
				{pedido}
				class="rounded-lg border border-gray-700 bg-gray-800 p-4 shadow-lg transition-colors duration-200 hover:bg-gray-700"
				on:marcarPronto={(e) => {
					e.detail.forEach((id) => atualizarFlagItem(id));
				}}
			/>
		{/each}
	</div>

	{#if mostrarHistorico}
		<HistoricModal
			pedidos={pedidosConcluidos}
			on:close={fecharHistorico}
			on:voltarAndamento={(e) => atualizarFlagItem(e.detail)}
			class="rounded-xl shadow-2xl"
		/>
	{/if}
</main>
