<template>
	<div class="container-global-index">
		<!-- Formulário de Pesquisa -->
    <div class="container search-form-location-container">
      <SearchFormLocation
        v-if="search.response.data"
        v-model="search"
        :loading="search.loading"
        @update:modelValue="(v, p) => searchHandler(v, p)"
        :priceRangeProps="search.response.data"
      />
    </div>

		<!-- Layout Principal -->
    <v-row class="w-100 mb-1 justify-content-end" :class="isMobile ? 'position-sticky z-3 mt-1' : ''" :style="isMobile ? 'top: 10px;' : ''">
      <br v-if="!isMobile"/>
      <v-btn v-if="!store.showMap && isMobile"
        color="primary"
        style="top: 0; z-index: 9999;"
        rounded="lg"
        @click="store.toggleShowMaps()"
      >
        <v-icon v-if="store.showMap" icon="mdi-format-list-numbered"></v-icon>
        <v-icon v-else icon="mdi-map-marker-radius"></v-icon>
      </v-btn> 
      <v-btn v-else
        color="primary"
        rounded="lg"
        @click="store.toggleShowMaps()"
      >
        <v-icon v-if="store.showMap" icon="mdi-format-list-numbered"></v-icon>
        <v-icon v-else icon="mdi-map-marker-radius"></v-icon>
      </v-btn> 
    </v-row>
    
		<v-row
			align="start"
			class="d-flex flex-grow-1 main-container p-0 m-0"
		>
			<!-- Coluna de Listagem -->
			<v-col
				:cols="store.showMap ? 6 : 12"
				:md="store.showMap ? 4 : 12"
        :lg="store.showMap ? 6 : 12"
				class="position-relative p-0"
			>
				<div class="position-relative text-center">
					<!-- Lista de Propriedades -->
					<v-row class="h-100 p-0 m-0 justify-content-center" >
						<!-- Loading -->
						<template v-if="search.loading && search.response.data.entities.length === 0">
							<v-col
								v-for="n in 12"
								:key="'loading-' + n"
								cols="12"
								:sm="store.showMap ? 12 : 6"
								:md="store.showMap ? 12 : 4"
								:lg="store.showMap ? 6 : 3"
								:xxl="store.showMap ? 3 : 2"
							>
								<v-skeleton-loader
									type="image, article"
									width="100%"
									class="pa-2 m-0 mb-3 bg-transparent"
								/>
							</v-col>
						</template>

						<!-- Nenhum Resultado -->
						<v-col
							v-if="!search.loading && search.response.data.entities.length === 0"
							cols="12"
						>
							<app-empty
								style="background: #e5e5e5; height: 100%; min-height: 500px;"
								text="No properties found"
							/>
						</v-col>

						<!-- Resultados -->
						<v-col
							v-for="p in search.response.data.entities"
							:key="p.id"
							cols="12"
							:sm="store.showMap ? 12 : 6"
							:md="store.showMap ? 12 : 4"
							:lg="store.showMap ? 6 : 3"
							:xxl="store.showMap ? 4 : 2"
						>
							<property-item :property="p"/>
						</v-col>

						<!-- Loading Progress -->
						<v-col class="text-center my-10 loading-properties" cols="12">
							<template v-if="isLimit">
								<v-progress-circular
									:size="50"
									color="primary"
									indeterminate
								/>
							</template>
						</v-col>
					</v-row>
				</div>
			</v-col>

			<!-- Coluna de Mapa -->
			<v-col
				v-if="store.showMap && !isMobile"
				:cols="6"
				:md="8"
        :lg="6"
				class="h-100 d-flex flex-column flex-grow-1 position-relative"
			>
        <div class="sticky-top" style="top: 12px;">
          <AppMap :properties="search.response.data.entities" style="height: 96vh; z-index: 1020;"/>
        </div>
			</v-col>
		</v-row>
	</div>

	<v-dialog v-if="isMobile" v-model="store.showMap" transition="dialog-bottom-transition" height="100%" fullscreen>
		<AppMap
			:properties="search.response.data.entities"
			style="position: static; padding: 0; margin: 0;"
			:isMobile="isMobile"
			class="maps"
		/>
		<v-btn
			text="Close"
			color="primary"
			elevation="12"
			rounded="lg"
			@click="store.setShowMaps(false)"
			style="position: absolute; bottom: 5px; width: 96%; z-index: 9999; left: 50%; transform: translate(-50%);"
		/>
	</v-dialog>
</template>

<script setup>
const {onBeforeMount, ref, computed, onMounted, onBeforeUnmount} = Vue;
const {useRoute} = VueRouter;
const store = usePropertiesMapsStore()

const SearchFormLocation = Vue.defineAsyncComponent(() =>
	loadModule(SAS_URL + "/src/components/shortcodes/property/SearchFormLocation.vue", options),
);
const AppEmpty = Vue.defineAsyncComponent(() =>
	loadModule(`${SAS_URL}/src/components/AppEmpty.vue`, options),
);
const PropertyItem = Vue.defineAsyncComponent(() =>
	loadModule(`${SAS_URL}/src/components/property/Item.vue`, options),
);
const AppMap = Vue.defineAsyncComponent(() =>
	loadModule(`${window.SAS_URL}/src/components/AppMap.vue`, options),
);

const search = useSasPropertySearch();
const page = ref(1);
const totalPages = ref(0);
const isLimit = ref(false);
const route = useRoute();

onBeforeMount(async () => {
	document.title = "Properties";
	setTimeout(() => {
		search.value.params = stringToObject(route.query);
	})

  if (isMobile.value)
    store.setShowMaps(false);
  else
    store.setShowMaps(true);

	await load(decodeURIComponent(window.location.search));

	observeIntersection(".loading-properties", callback, {threshold: 0.2}, 3000);
});

// const args = computed(() => {
// 	console.log(route)
// 	const {params} = route.currentRoute;
// 	return {
// 		search: {slug: `${params.id}/${params.slug}`},
// 	};
// });

const callback = async (entries, observer) => {
	isLimit.value = entries[0].isIntersecting;

	if (isLimit.value && !search.loading && (page.value < totalPages.value)) {
		await seeMoreProperties();

		if (page.value === totalPages.value) {
			observer.unobserve(entries[0].target);
		}
	} else {
		isLimit.value = false
	}
};

const stringToObject = (queryString) => {
	const formattedData = {};
	Object.entries(queryString).forEach(([key, value]) => {
		const matches = key.match(/^search\[(.*?)\]$/);
		const arrayMatches = key.match(/^search\[(.*?)\]\[\]$/);
		if (arrayMatches) {
			const searchKey = arrayMatches[1];
			if (!formattedData.search) {
				formattedData.search = {};
			}
			formattedData.search[searchKey] = Array(value) ? value.map(num => Number(num)) : value ;
			return
		}
		if (matches && matches.length === 2) {
			const searchKey = matches[1];
			if (!formattedData.search) {
				formattedData.search = {};
			}
			formattedData.search[searchKey] = value;
		}
	});

	return formattedData;
};

const seeMoreProperties = async () => {
	page.value += 1;
	await load(decodeURIComponent(window.location.search));
	isLimit.value = false
};

const load = async (payload) => {
	if (payload !== "") {
		payload = `&${payload}`;
	}
	try {
		if (search.value.loading) return
		search.value.loading = true;
		const {data} = await axios.get(
			`/properties/wordpress/search?per_page=12&page=${page.value}${payload}`,
		);

		search.value.response.data.entities.push(...data.data.entities);
		search.value.response.data.max_price = data.data.max_price;
		search.value.response.data.min_price = data.data.min_price;
		page.value = data.data.pagination.current_page;
		totalPages.value = data.data.pagination.total_pages;
	} catch (e) {
		console.log(e);
	} finally {
		search.value.loading = false;
		isLimit.value = false
	}
};

const searchHandler = async (data, payload) => {
	page.value = 1;
	// search.value.params.search = data;
	search.value.response.data.entities = [];
	await load(payload);
};

const isMobile = computed(() => {
	return window.screen.width <= 700;
});

onMounted(() => {
	updateViewportHeight();
	window.addEventListener('resize', updateViewportHeight);
})
onBeforeUnmount(() => {
	window.removeEventListener('resize', updateViewportHeight);
})
const updateViewportHeight = () => {
	const vh = window.innerHeight * 0.01;
	document.documentElement.style.setProperty('--vh', `${vh}px`);
}

</script>
<style scoped>
.main-container {
	flex-grow: 1;
	min-height: 100vh;
	position: relative;
}

@media (min-width: 1400px) {
  .search-form-location-container {
    max-width: 1170px;
  }
}

@media (max-width: 380px) {
  .search-form-location-container {
    padding: 0;
    margin-top: 10px;
  }
}
/*
@media (min-width: 992px) {
  .search-form-location-container {
    max-width: 960px;
  }
}

@media (min-width: 1200px) {
  .search-form-location-container {
    max-width: 1140px;
    padding: 0;
  }
}

 @media (min-width: 1400px) {
  .search-form-location-container {
    max-width: 1320px;
  }
} */


.maps {
	height: calc(var(--vh, 1vh) * 100) !important;
}
</style>
