<script>
	import { onMount, tick } from 'svelte';
	import QRScanner from './QRScanner.svelte';

	let scanned_id = $state('');
	let scan_user = $state('Roman');
	let scan_data = $state({});
	let ticket_state = $state('not_scanned');

    onMount(() => {reset_scan_data()});

	function reset_scan_data() {
		ticket_state = 'unknown';
		scan_data = {
			id: 0,
			created_at: 'none',
			name: 'none',
			surname: 'none',
			email: 'none@esnvutbrno.cz',
			uuid: 'none',
			scanned: 'none',
			scanned_at: 'none',
			event_name: 'none',
			scanned_by: 'none'
		};
	}

	$effect(() => {
		if (scan_data.scanned === true) {
			ticket_state = 'Already scanned';
		} else if (scan_data.scanned === false) {
			ticket_state = 'Good to go in 2';
            console.log(scan_data.scanned);
		} else {
            ticket_state = 'Ticket invalid';
        }
	});

	$effect(() => {
		console.log('Message updated:', scanned_id);
        
		reset_scan_data();
        fetch('https://n8n.orebolt.cz/webhook/9d32752c-47c9-46db-be6d-f473e97a7c25', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({ scanned_id, scan_user })
		})
			.then((response) => response.json())
			.then((data) => {
				scan_data = data;
				console.log('Success:', data);
			})
			.catch((error) => {
                console.error('Error:', error);
                ticket_state = "Ticket invalid";
            });
	});
</script>

<QRScanner bind:message={scanned_id} />

<p>CODE: {scanned_id}</p>

<p>Name: {scan_data.name} {scan_data.surname}</p>
<p>State: {ticket_state}</p>
<p>Event: {scan_data.event_name}</p>
