<script>
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	import { browser } from '$app/environment';
	import save_icon from '$lib/assets/save_icon.svg';
	import arrow_back from '$lib/assets/arrow_back.svg';

	let token = null;
	let companyId = null;
	let userId = null;
	let tableId = null;
	let flag = null;
	let orderToCancel = null;

	if (browser) {
		token = localStorage.getItem('token');
		companyId = Number(localStorage.getItem('company'));
		userId = localStorage.getItem('user');
		tableId = Number(localStorage.getItem('table'));
		flag = localStorage.getItem('flag');
	}

	let orders = [];
	let isCreatingOrder = false;
	let customerName = '';
	let customerPhone = '';
	let showConfirmCancel = false;

	const fetchOrders = async () => {
		if (!companyId || !tableId) return;
		try {
			const response = await fetch('https://dev2.mixtech.dev.br/order/get', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${token}`
				},
				body: JSON.stringify({ company_id: companyId, table_id: tableId })
			});
			const result = await response.json();

			if (result.status === 'ok') {
				orders = result.data.map((o) => ({
					id: o.order_id,
					name: o.order_name,
					phone: o.order_phone,
					createdAt: o.order_created_at,
					status: o.status_status
				}));
			} else {
				console.error('Failed to fetch orders:', result.msg);
			}
		} catch (err) {
			console.error('Request error:', err);
		}
	};

	const openOrder = (orderId) => {
		goto(`/pos/${orderId}`);
	};

	const createOrder = async () => {
		if (!customerName.trim()) return;
		try {
			const response = await fetch('https://dev2.mixtech.dev.br/order/create', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${token}`
				},
				body: JSON.stringify({
					table_id: tableId,
					user_name: userId,
					company_id: companyId,
					order_name: customerName,
					order_phone: customerPhone || '',
					status_status: 'Aberta'
				})
			});
			const result = await response.json();
			if (result.status === 'ok') {
				isCreatingOrder = false;
				customerName = '';
				customerPhone = '';
				await fetchOrders();
			} else {
				console.error('Failed to create order:', result.msg);
			}
		} catch (err) {
			console.error('Error creating order:', err);
		}
	};

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

		const raw = JSON.stringify({
			order_id: order_Id,
			company_id: companyId,
			cancel: true
		});

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

		fetch('https://dev2.mixtech.dev.br/order/delete', requestOptions)
			.then((response) => response.json())
			.then((result) => {
				//(console.log('Pedido cancelado com sucesso:', order_Id, companyId, result), fetchOrders());
			})
			.catch((error) => console.error('Erro ao cancelar comanda:', error));
	}

	const getElapsedTime = (createdAt) => {
		if (!createdAt || createdAt.trim() === '') return '';
		const start = new Date(createdAt.replace(' ', 'T'));
		const now = new Date();
		const diff = Math.floor((now - start) / 60000); // in minutes

		if (diff < 60) return `${diff} min`;
		const hours = Math.floor(diff / 60);
		const minutes = diff % 60;
		return `${hours}h ${minutes}m`;
	};

	function handleAddProduct(order_id) {
		localStorage.setItem('order', order_id);
		goto('/dashboard/addproducts');
	}
	function handleEndProduct(order_id) {
		localStorage.setItem('order', order_id);
		goto('/dashboard/endcommand');
	}

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

<div class="mb-6 flex w-full items-center">
	<button
		on:click={() => goto('/dashboard/tables')}
		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>
</div>
<div class="container mx-auto w-full rounded-md bg-gray-800 p-4">
	<h1 class="mb-6 text-center text-2xl font-bold">Comandas</h1>
	<div
		class="grid grid-cols-2 justify-items-center gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5"
	>
		{#each orders as order}
			<div
				class="w-full max-w-xs rounded-lg bg-gray-900 shadow-md transition-transform hover:scale-105"
			>
				<div class="flex flex-col items-center justify-between rounded-t-lg bg-emerald-700 p-4">
					<span class="font-medium">{order.name}</span>
					<span class="font-medium">{order.phone}</span>
				</div>
				<div class="p-4">
					<div class="mb-2 text-sm text-gray-400">
						{getElapsedTime(order.createdAt)}
					</div>
					<!--adicionar aqui link para o addproduct preciso salvar uma variavel com o order_id e etc para aparecer apenas o item da comanda em especifico-->
					<button
						class="mb-2 w-full rounded bg-emerald-600 py-2 hover:bg-emerald-700"
						on:click={handleAddProduct(order.id)}
					>
						Adicionar items
					</button>
					{#if flag == 'cashier' || flag == 'admin'}
						<button
							class="mb-2 w-full rounded bg-yellow-600 py-2 hover:bg-yellow-700"
							on:click={handleEndProduct(order.id)}
						>
							Finalizar Comanda
						</button>
					{/if}
					{#if flag == 'admin'}
						<button
							class="w-full rounded bg-red-600 py-2 hover:bg-red-700"
							on:click={cancelCommand(order.id)}
						>
							Cancelar
						</button>
					{/if}
				</div>
			</div>
		{/each}
	</div>
	<div class="mt-6 flex justify-center">
		<button
			class="rounded-md bg-green-600 px-4 py-2 text-white hover:bg-green-700"
			on:click={() => (isCreatingOrder = true)}
		>
			Adicionar Comanda
		</button>
	</div>
</div>
{#if isCreatingOrder}
	<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">New Order</h2>
			<form on:submit|preventDefault={createOrder} class="space-y-4">
				<div>
					<p class="mb-1 block text-sm text-gray-400">Nome</p>
					<input
						bind:value={customerName}
						placeholder="Ex: John Doe"
						class="w-full rounded-md border border-gray-600 bg-gray-700 px-3 py-2 focus:ring-emerald-500"
					/>
				</div>
				<div>
					<p class="mb-1 block text-sm text-gray-400">Numero (optional)</p>
					<input
						bind:value={customerPhone}
						placeholder="(11) 99999-9999"
						class="w-full rounded-md border border-gray-600 bg-gray-700 px-3 py-2 focus:ring-emerald-500"
					/>
				</div>

				<div class="flex justify-end space-x-2">
					<button
						type="button"
						on:click={() => (isCreatingOrder = false)}
						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="Save" class="mr-2 h-4 w-4" /> Salvar
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}
{#if showConfirmCancel}
	<div class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50">
		<div class="w-full max-w-sm rounded-lg bg-gray-800 p-6">
			<h2 class="mb-4 text-lg font-bold">Confirmar Exclusão</h2>
			<p class="mb-4">Deseja realmente cancelar a comanda {orderToCancel}?</p>
			<div class="flex justify-end gap-2">
				<button
					on:click={() => (showConfirmCancel = false)}
					class="rounded bg-gray-600 px-4 py-2 text-white transition-colors hover:bg-gray-700"
				>
					Cancelar
				</button>
				<button
					on:click={deleteTable}
					class="rounded bg-red-600 px-4 py-2 text-white transition-colors hover:bg-red-700"
				>
					Excluir
				</button>
			</div>
		</div>
	</div>
{/if}
