<script lang="ts">
	import { enhance } from '$app/forms';
	import ComboBox from '$lib/components/ComboBox.svelte';
	import Footer from '$lib/components/Footer.svelte';
	import TwoCities from '$lib/components/TwoCities.svelte';
	import type { CityBasic, CountryBasic, ComboOption } from '$lib/types';
	import type { PageProps } from './$types';

	let { data }: PageProps = $props();

	let filteredCities: CityBasic[] = $state([]);

	const setCountryCities = (id: number | null) => {
		if (id) {
			filteredCities = data.cities.filter((c) => c.country_id == id);
		} else {
			filteredCities = [];
		}
	};

	const onCountrySelect = (country: CountryBasic | ComboOption) => {
		setCountryCities(country.id);
	};
</script>

<svelte:head>
	<title>HotColdCities</title>
</svelte:head>

<main class="flex h-full min-h-screen flex-col bg-white">
	<div class="container mx-auto my-3 max-w-4xl flex-grow p-4">
		<h1 class="my-5 text-center text-4xl font-light">HotColdCities</h1>
		<h2 class="mx-auto max-w-xl text-center text-xl leading-tight md:text-2xl">
			Compare the hottest 🌡️ and coldest ❄️ cities in any region to plan 📅, move 🚚, or explore 🌍
			with ease! 🎉✨
		</h2>
		<!-- TODO: Add tabs to select between countries select or two cities  -->
		<section class="mx-auto my-8 flex w-full justify-center">
			<div class="flex flex-col gap-2 w-full">
				<div class="w-full max-w-md mx-auto">
					<ComboBox
					options={data.countries}
					onSelect={onCountrySelect}
					onClear={() => setCountryCities(null)}
					/>
				</div>
				<!-- Add badges top  7 popular countries -->
				<ul class="flex flex-col gap-1">
					{#each filteredCities as city (city.id)}
						<li class="flex gap-2">
							{city.name}
							<form action="?/fetchTemperature" method="POST" use:enhance>
								<input type="text" class="hidden" name="latitude" value={city.latitude} />
								<input type="text" class="hidden" name="longitude" value={city.longitude} />
								<button type="submit" class="btn btn-soft btn-primary">Get</button>
							</form>
						</li>
					{/each}
				</ul>
			</div>
		</section>
		<!-- TODO: Show max min temperatures in the country and its coresponding cities -->

		<section>
			<!-- <TwoCities cities={data.cities} /> -->
		</section>
	</div>
	<Footer />
</main>
