<script lang="ts">
	import { applyAction, enhance } from '$app/forms';
	import { pushState, replaceState } from '$app/navigation';
	import ComboBox from '$lib/components/ComboBox.svelte';
	import Footer from '$lib/components/Footer.svelte';
	import Navbar from '$lib/components/Navbar.svelte';
	import TwoCities from '$lib/components/TwoCities.svelte';
	import { units, unitsSymbol } from '$lib/helpers/stores';
	import { celsiusToFahrenheit } from '$lib/helpers/utils';
	import {
		type CityBasic,
		type CountryBasic,
		type ComboOption,
		type HotColdCity,
		UnitsEnum
	} from '$lib/types';
	import type { PageProps } from './$types';

	let { data, form }: PageProps = $props();
	let temperatureData: HotColdCity[] | null = $state(data.temperatureData);
	let tempDiff: number | null = $derived(
		temperatureData ? Number((Math.abs(temperatureData[0].max_temp - temperatureData[1].max_temp)).toFixed(2)) : null
	);
	let selectedCountryId: number | null = $state(data.country_id);
	let countryForm: HTMLFormElement;
	let submitButton: HTMLButtonElement;
	let countryIdInput: HTMLInputElement;
	// let filteredCities: CityBasic[] = $derived(
	// 	data.cities.filter((c) => c.country_id == selectedCountryId)
	// );

	const onCountrySelect = async (country: CountryBasic | ComboOption) => {
		selectedCountryId = country.id;
		countryIdInput.value = selectedCountryId.toString();
		pushState(`?country=${selectedCountryId}`, { country: selectedCountryId });
		submitButton.click();
	};

	const handleClearCountry = () => {
		replaceState('/', {});
		selectedCountryId = null;
	};

	$effect(() => {
		if (form && form.ok) {
			temperatureData = form.data;
		}
	});
</script>

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

<main class="flex h-full min-h-screen flex-col overflow-x-hidden bg-white">
	<Navbar />
	<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 w-full flex-col gap-2">
				<div class="mx-auto w-full max-w-md">
					<ComboBox
						options={data.countries as readonly CountryBasic[]}
						onSelect={onCountrySelect}
						selectedOptionId={selectedCountryId}
						onClear={handleClearCountry}
					/>
				</div>
				<form
					action="?/fetchTemperature"
					method="POST"
					class="hidden"
					use:enhance={() => {
						return async ({ result }) => {
							await applyAction(result);
						};
					}}
					bind:this={countryForm}
				>
					<input type="number" name="country_id" bind:this={countryIdInput} readonly />
					<button type="submit" bind:this={submitButton}>Submit</button>
				</form>
				{#if selectedCountryId && temperatureData}
					<div class="my-8 flex flex-col justify-evenly gap-12 md:flex-row">
						{#each temperatureData as temperature}
							<dl class="flex flex-col gap-2">
								{#if temperature.coldest_rank === 1}
									<dt class="text-center text-lg text-blue-600">❄️ Coldest City</dt>
								{:else}
									<dt class="text-center text-lg text-red-600">🌡️ Hottest City</dt>
								{/if}
								<dt class="text-center text-3xl font-medium">{temperature.city_name}</dt>
								<dd>
									Max: {$units == UnitsEnum.IMPERIAL
										? celsiusToFahrenheit(temperature.max_temp)
										: temperature.max_temp}{$unitsSymbol}
								</dd>
							</dl>
						{/each}
						{#if tempDiff}
							<div class="text-center">
								<p class="text-lg font-medium">Temperature Difference</p>
								<p class="text-2xl">
									{$units == UnitsEnum.IMPERIAL
										? celsiusToFahrenheit(tempDiff)
										: tempDiff}{$unitsSymbol}
								</p>
							</div>
						{/if}
					</div>
				{/if}
				<!-- 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="country_id"
									readonly
									bind:value={selectedCountryId}
								/>
								<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>
