<template>
	<v-combobox
		v-model="selectionProperty"
		label="Single Property Selection"
		:items="properties"
		item-title="properties.name"
		item-value="properties.id"
		variant="outlined"
		clearable
		bg-color="white"
		:loading="loading"
		return-object
		@update:model-value="handleInput"
	></v-combobox>
</template>

<script setup>
const {ref, defineEmits, onMounted} = Vue;

const emit = defineEmits(['selectProperty']);
const debounceTimeout = ref(null);
const loading = ref(false);
const selectionProperty = ref(null);
let currentController = null;
const properties = ref([]);

onMounted(() => {
	if (!!propertyData) {
		selectionProperty.value = propertyData
	}
})

const handleInput = (value) => {
	if (typeof value === 'object') {
		document.getElementById('sas_one_property_page_id').value = value?.properties?.id;

		return;
	}

	if (debounceTimeout.value) clearTimeout(debounceTimeout.value);

	debounceTimeout.value = setTimeout(() => {
		if (value.length >= 3) {
			searchProperties(value);
		}
	}, 800);
};

const searchProperties = async (query) => {
	if (currentController) {
		currentController.abort();
	}

	currentController = new AbortController();

	try {
		properties.value = []
		loading.value = true;
		const {data} = await axios.get("properties/external", {
			params: {property_filter_name: query, page: 1, per_page: 999999},
			signal: currentController.signal,
		});

		properties.value = data.data.entities;
	} catch (error) {
		if (axios.isCancel(error)) {
			console.log("Previous request canceled for:", query);
		} else {
			console.error("Error fetching properties:", error);
		}
	} finally {
		loading.value = false;
	}
};
</script>
