let uploadFileInput = document.getElementById('imgUpload');
let fileName = document.getElementById('fileName');
let imgUploadForm = document.getElementById('imgUploadForm');
let scannerField = document.getElementById('scannerField');
let btn_restock = document.getElementById('btn_restock');

let btn_save_2 = document.getElementById('btn_save_2');

let form_gtin = document.getElementById('form_gtin');

let modal_stage_1 = document.getElementById('modal-stage-1');
let modal_stage_2 = document.getElementById('modal-stage-2');
let modal_stage_3 = document.getElementById('modal-stage-3');

let modal_stage_2_result = document.getElementById("stage-2-result");

let modal_stage_2_amount = document.getElementById("stage-2-amount");

let globalData;

waitingForScan = false;
let currentRestockProduct = null;


function handleImagePresence(row) {
	// Check if /api/v1/image?id=row&check returns true
	// Needs to be sync

	let isThere = false;
	const xhr = new XMLHttpRequest();
	xhr.open('GET', `/api/v1/image?id=${row.id}&check=true`, false);
	xhr.send();
	if (xhr.status === 200) {
		try {
			isThere = JSON.parse(xhr.responseText);
		} catch (error) {
			console.error(error);
			isThere = false;
		}
		
	}
	
	let pretty = isThere ? '<i class="bi bi-check"></i>' : '<i class="bi bi-x"></i></a>';
	const template = `<a href="/api/v1/image?id=${row.id}" target="_blank">${pretty}</a> <i class="bi bi-dot"></i> <button class="btn btn-primary" onclick="uploadImage(${row.id})"><i class="bi bi-upload"></i></button>`;
	return template;
}

function uploadImage(id) {
	// Open a file picker
	uploadFileInput.click();
	// // Open a modal to upload an image
	// // Use a form
	// const modal = document.getElementById('imageModal');
	// modal.style.display = 'block';
	imgUploadForm.action = `/api/v1/image?id=${id}`;
}

function silentFormSubmit() {
	// Submit the form silently (without reloading the page or redirecting)
	// Grab the form and do a POST request (dont forget to prevent default)
	const xhr = new XMLHttpRequest();
	xhr.open('POST', imgUploadForm.action, true);
	xhr.send(new FormData(imgUploadForm));
	xhr.onreadystatechange = function() {
		if (xhr.readyState === 4 && xhr.status === 200) {
			console.log(xhr.responseText);
			//location.reload();
			createTemporaryNotification('Bild hochgeladen', 'is-success');
			// Close the modal
			document.getElementById('imageModal').style.display = "none";

			// Empty the input
			uploadFileInput.value = '';
		}
	};
}

function enableScanner() {
	waitingForScan = true;
	scannerField.focus();
}

uploadFileInput.addEventListener('change', function() {
	fileName.innerHTML = this.files[0].name;
	silentFormSubmit();
	setTimeout(() => {
		refreshTableByName('products');
	}, 1000);
});

scannerField.style.fontSize = '1px';
scannerField.style.height = '1px';
scannerField.style.width = '1px';
scannerField.style.opacity = '0';
scannerField.style.position = 'relative';

// Make sure text fields is always centerd vertically
window.addEventListener('scroll', function(event) {
	if(!waitingForScan) {
		return;
	}
	scannerField.y = document.documentElement.scrollTop + 20;
	scannerField.style.top = document.documentElement.scrollTop + 20 + "px";
});

setInterval(() => {
	if(!waitingForScan) {
		return;
	}
	scannerField.focus();
}, 1000);

btn_restock.addEventListener('click', function() {
	modal_stage_1.classList.remove('is-hidden');
	modal_stage_2.classList.add('is-hidden');
	modal_stage_3.classList.add('is-hidden');
	waitingForScan = true;
});
// Handle barcode scanner input
scannerField.addEventListener('keydown', async function(event) {
	if(event.key != 'Enter') {
		return;
	}
	let barcode = scannerField.value;
	console.log('Barcode scanned:', barcode);
	scannerField.value = "";
	// createTemporaryNotification(`Barcode ${barcode} gescannt`, 'is-info');
	waitingForScan = false;

	// Check if barcode is in the database
	let product = globalData.find(p => p.gtin == barcode);
	if(product) {
		console.log('Product found:', product);
		currentRestockProduct = product;
		modal_stage_2_amount.innerHTML = "Aktuelle Menge: " + product.stock;
		modal_stage_1.classList.add('is-hidden');
		modal_stage_2.classList.remove('is-hidden');
		modal_stage_3.classList.add('is-hidden');
		createTemporaryNotification(`<i class="bi bi-upc-scan"></i> Barcode scan: GTIN ${barcode} gefunden`, 'is-success');
	} else {
		modal_stage_1.classList.add('is-hidden');
		modal_stage_2.classList.add('is-hidden');
		modal_stage_3.classList.remove('is-hidden');
		form_gtin.value = barcode;
	}
	// modal_stage_2_result.innerHTML = product ? `<i class="bi bi-check"></i> Produkt gefunden: ${product.name}` : `<i class="bi bi-x"></i> Produkt nicht gefunden`;
	


	// let product = globalData.find(p => p.gtin == barcode);
	// if(product) {
	// 	let event = new Event('click');
	// 	createTemporaryNotification(`<i class="bi bi-upc-scan"></i> Barcode scan: GTIN ${barcode} gefunden`, 'is-success');
	// 	document.getElementById(`product_${product.id}`).dispatchEvent(event);
	// } else {
	// 	createTemporaryNotification( `<i class="bi bi-upc-scan"></i> Barcode scan: GTIN ${barcode} nicht gefunden`, 'is-danger');
	// }
});

function restock(amount) {
	currentRestockProduct.stock += amount;
	modal_stage_2_amount.innerHTML = "Aktuelle Menge: " + currentRestockProduct.stock;
}

function applyStock() {
	let result = _api.patch('products', {
		"id": currentRestockProduct.id,
		"stock": currentRestockProduct.stock
	})
	if(result) {
		createTemporaryNotification('Bestand erfolgreich aktualisiert', 'is-success');
		modal_stage_2.classList.add('is-hidden');
		modal_stage_1.classList.remove('is-hidden');
		modal_stage_3.classList.add('is-hidden');
		enableScanner();
	} else {
		createTemporaryNotification('Fehler beim Aktualisieren des Bestands', 'is-danger');
	}


}

document.addEventListener('DOMContentLoaded', async function() {
	let data = await returnTableDataByTableName('products');
	console.info(`Found ${data.count} products`);
	const result = data.result;
	globalData = result;
});

// btn_save_2.addEventListener('click', async function() {
// 	// Assume submission is valid
// 	// Get the form data
// 	// reload table
// 	// close modal
// });