<script>
	import { goto } from '$app/navigation';
	import { onMount } from 'svelte';
	import { browser } from '$app/environment';

	let token = null;
	let company = null;
	let flag = null;
	let orders = {};
	let tableHasOrders = {};

	if (browser) {
		token = localStorage.getItem('token');
		company = Number(localStorage.getItem('company'));
		flag = localStorage.getItem('flag');
	}

	const statusMap = {
		1: 'FREE',
		2: 'OCCUPIED',
		3: 'ALERT'
	};

	const statusToApiMap = {
		FREE: 'Livre',
		OCCUPIED: 'Ocupado',
		ALERT: 'Alerta'
	};

	let tables = [];
	let newTableNumber = '';
	let showConfirmDelete = false;
	let tableToDelete = null;

	const getTableOrder = (tableId) => orders[tableId];

	const updateTableStatus = async (tableNumber, newStatus) => {
		const requestOptions = {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				Authorization: `Bearer ${token}`
			},
			body: JSON.stringify({
				table_number: tableNumber,
				company_id: company,
				status_status: statusToApiMap[newStatus]
			})
		};

		const response = await fetch('https://dev2.mixtech.dev.br/table/update', requestOptions);
		const result = await response.json();
		if (result.status !== 'ok') {
			throw new Error('Falha ao atualizar status: ' + result.msg);
		}
		fetchTables();
	};

	const startOrder = async (tableId, tableNumber) => {
		await updateTableStatus(tableNumber, 'OCCUPIED');
		tables = tables.map((t) =>
			t.id === tableId ? { ...t, status: 'OCCUPIED', startTime: new Date().toISOString() } : t
		);
		orders = { ...orders, [tableId]: { items: [], totalAmount: 0 } };
	};

	const getStatusColor = (status) => {
		switch (status) {
			case 'FREE':
				return 'bg-green-600 hover:bg-green-700';
			case 'OCCUPIED':
				return 'bg-yellow-500 hover:bg-yellow-600';
			default:
				return 'bg-gray-700 hover:bg-gray-800';
		}
	};

	const getStatusText = (status) => {
		switch (status) {
			case 'FREE':
				return 'Livre';
			case 'OCCUPIED':
				return 'Ocupada';
			default:
				return 'Desconhecido';
		}
	};

	const handleTableClick = async (tableId, tableNumber) => {
		const table = tables.find((t) => t.id === tableId);
		if (!table) return;

		if (table.status === 'FREE') {
			await startOrder(tableId, tableNumber);
			localStorage.setItem('table', table.id);
			goto('/dashboard/commands');
		}
		localStorage.setItem('table', table.id);
		goto('/dashboard/commands');
	};

	const openDeleteConfirm = (tableId, tableNumber) => {
		tableToDelete = { id: tableId, number: tableNumber };
		showConfirmDelete = true;
	};

	const cancelDelete = () => {
		showConfirmDelete = false;
		tableToDelete = null;
	};

	const deleteTable = async () => {
		if (!tableToDelete) return;

		const requestOptions = {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				Authorization: `Bearer ${token}`
			},
			body: JSON.stringify({
				table_number: tableToDelete.number,
				company_id: company
			})
		};

		try {
			const response = await fetch('https://dev2.mixtech.dev.br/table/delete', requestOptions);
			const result = await response.json();
			if (result.status === 'ok') {
				tables = tables.filter((t) => t.id !== tableToDelete.id);
				delete orders[tableToDelete.id];
				orders = { ...orders };
				showConfirmDelete = false;
				tableToDelete = null;
			} else {
				console.error('Erro ao excluir mesa:', result.msg);
			}
		} catch (error) {
			console.error(error);
		}
	};
	let showLiberarMesa = {};
	const fetchTables = async () => {
		const requestOptions = {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				Authorization: `Bearer ${token}`
			},
			body: JSON.stringify({ company_id: company })
		};

		try {
			const response = await fetch('https://dev2.mixtech.dev.br/table/get', requestOptions);
			const result = await response.json();

			if (result.status === 'ok') {
				tables = result.data.map((d) => ({
					id: d.table_id,
					number: d.table_number,
					status: statusMap[d.status_id] || 'Desconhecido',
					statusId: d.status_id,
					startTime: statusMap[d.status_id] === 'FREE' ? null : new Date().toISOString()
				}));

				// Inicializa orders, para evitar undefined
				tables.forEach((t) => {
					if (t.status !== 'FREE' && !orders[t.id]) {
						orders[t.id] = { items: [], totalAmount: 0 };
					}
				});

				orders = { ...orders };

				await Promise.all(
					tables.map(async (t) => {
						try {
							const orderResp = await fetch('https://dev2.mixtech.dev.br/order/get', {
								method: 'POST',
								headers: {
									'Content-Type': 'application/json',
									Authorization: `Bearer ${token}`
								},
								body: JSON.stringify({
									company_id: company,
									table_id: t.id
								})
							});

							const text = await orderResp.text();

							// Se resposta vazia ou inválida, considerar sem pedidos
							if (!text.trim()) {
								showLiberarMesa[t.id] = t.statusId !== 1; // só liberar se status diferente de 1
								return;
							}

							let orderResult;
							try {
								orderResult = JSON.parse(text);
							} catch {
								showLiberarMesa[t.id] = t.statusId !== 1;
								return;
							}

							// Lógica para mostrar botão liberar mesa:
							// Mesa ocupada (statusId != 1) e sem pedidos (data vazio)
							showLiberarMesa[t.id] =
								t.statusId !== 1 && (orderResult.status !== 'ok' || orderResult.data.length === 0);
						} catch (e) {
							console.error('Erro ao checar pedidos da mesa', t.id, e);
							showLiberarMesa[t.id] = false;
						}
						showLiberarMesa = { ...showLiberarMesa };
					})
				);
			} else {
				console.error('Erro ao buscar mesas:', result.msg);
			}
		} catch (error) {
			console.error(error);
		}
	};
	const createTable = async () => {
		if (!newTableNumber) return;

		const requestOptions = {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				Authorization: `Bearer ${token}`
			},
			body: JSON.stringify({
				company_id: company,
				table_number: newTableNumber,
				status_id: 1
			})
		};

		try {
			const response = await fetch('https://dev2.mixtech.dev.br/table/create', requestOptions);
			const result = await response.json();
			if (result.status === 'ok') {
				await fetchTables();
				newTableNumber = '';
			} else {
				console.error('Erro ao criar mesa:', result.msg);
			}
		} catch (error) {
			console.error(error);
		}
	};

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

<div class="container mx-auto">
	<div class="flex flex-col">
		<h1 class="mb-6 text-2xl font-bold">Mesas</h1>

		{#if flag === 'admin'}
			<div class="mb-4 flex">
				<input
					bind:value={newTableNumber}
					placeholder="Número da nova mesa"
					class="flex-grow rounded-l-md bg-gray-700 px-4 py-2 text-white focus:outline-none"
				/>
				<button
					on:click={createTable}
					class="rounded-r-md bg-blue-600 px-4 py-2 text-white transition-colors hover:bg-blue-700"
				>
					Criar Mesa
				</button>
			</div>
		{/if}

		<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
			{#each tables as table, i}
				{@const order = getTableOrder(table.id)}

				<div
					class="transform overflow-hidden rounded-lg bg-gray-800 shadow-md transition-transform duration-200 hover:scale-105"
				>
					<div class={`flex items-center justify-between p-4 ${getStatusColor(table.status)}`}>
						<span class="font-medium">Mesa {table.number}</span>
						<span class="text-sm font-medium">{getStatusText(table.status)}</span>
					</div>

					<div class="p-4">
						{#if table.status !== 'FREE' && order}
							<button
								on:click={() => handleTableClick(table.id, table.number, i)}
								class="mt-2 flex w-full items-center justify-center rounded bg-indigo-600 px-3 py-2 text-sm transition-colors hover:bg-indigo-700"
							>
								Detalhes Mesa
							</button>
						{:else}
							<div class="flex flex-col items-center justify-center space-y-2 py-4">
								<button
									on:click={() => handleTableClick(table.id, table.number, i)}
									class="flex items-center justify-center rounded bg-emerald-600 px-4 py-2 transition-colors hover:bg-emerald-700"
								>
									Abrir Mesa
								</button>
								{#if flag === 'admin'}
									<button
										on:click={() => openDeleteConfirm(table.id, table.number)}
										class="flex items-center justify-center rounded bg-red-600 px-4 py-2 text-sm transition-colors hover:bg-red-700"
									>
										Excluir Mesa
									</button>
								{/if}
							</div>
						{/if}

						{#if showLiberarMesa[table.id]}
							<button
								on:click={() => updateTableStatus(table.number, 'FREE')}
								class="mt-2 flex w-full items-center justify-center rounded bg-emerald-600 px-3 py-2 text-sm transition-colors hover:bg-emerald-700"
							>
								Liberar Mesa
							</button>
						{/if}
					</div>
				</div>
			{/each}
		</div>
	</div>
</div>

{#if showConfirmDelete}
	<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 excluir a Mesa {tableToDelete?.number}?</p>
			<div class="flex justify-end gap-2">
				<button
					on:click={cancelDelete}
					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}
