<script lang="ts">
	import * as AlertDialog from "$lib/components/ui/alert-dialog/index.js";
	import { ckFlowVM } from "$lib/domains/ckflow/view/ckflow.vm.svelte";
	import { flightTicketVM } from "../ticket.vm.svelte";
	import ButtonLoadableText from "$lib/components/atoms/button-loadable-text.svelte";
	import Title from "$lib/components/atoms/title.svelte";
	import { convertAndFormatCurrency } from "$lib/domains/currency/view/currency.vm.svelte";

	async function onPriceUpdateConfirm() {
		if (!ckFlowVM.updatedPrices) {
			return;
		}
		await flightTicketVM.updateTicketPrices(ckFlowVM.updatedPrices);
		ckFlowVM.clearUpdatedPrices();
	}

	function cancelBooking() {
		window.location.replace("/search");
	}

	let open = $state(false);

	$effect(() => {
		open = !!ckFlowVM.updatedPrices;
	});
</script>

<AlertDialog.Root bind:open>
	<AlertDialog.Content>
		<AlertDialog.Header>
			<AlertDialog.Title>The price has changed!</AlertDialog.Title>
			<AlertDialog.Description>
				Ticket prices change throughout the day and, unfortunately, the
				price has been changed since last we had checked. You can continue
				with the new price or check out alternative trips.
			</AlertDialog.Description>
		</AlertDialog.Header>

		<div class="flex flex-col gap-1">
			<Title size="h5" color="black">New Price</Title>

			<Title size="h4" color="black" weight="semibold">
				{convertAndFormatCurrency(
					ckFlowVM.updatedPrices?.displayPrice ?? 0,
				)}
			</Title>
		</div>
		<AlertDialog.Footer>
			<AlertDialog.Cancel
				disabled={flightTicketVM.updatingPrices}
				onclick={() => cancelBooking()}
			>
				Go Back
			</AlertDialog.Cancel>
			<AlertDialog.Action
				disabled={flightTicketVM.updatingPrices}
				onclick={() => onPriceUpdateConfirm()}
			>
				<ButtonLoadableText
					loading={flightTicketVM.updatingPrices}
					text={"Continue"}
					loadingText={"Updating..."}
				/>
			</AlertDialog.Action>
		</AlertDialog.Footer>
	</AlertDialog.Content>
</AlertDialog.Root>
