<script lang="ts">
	import Title from "$lib/components/atoms/title.svelte";
	import { Badge } from "$lib/components/ui/badge/index.js";
	import Button, {
		buttonVariants,
	} from "$lib/components/ui/button/button.svelte";
	import * as Dialog from "$lib/components/ui/dialog/index.js";
	import { TRANSITION_ALL } from "$lib/core/constants";
	import { convertAndFormatCurrency } from "$lib/domains/currency/view/currency.vm.svelte";
	import { cn } from "$lib/utils";
	import { type FlightTicket } from "../../data/entities";
	import { flightTicketVM } from "../ticket.vm.svelte";
	import TicketDetailsModal from "./ticket-details-modal.svelte";
	import TicketLegsOverview from "./ticket-legs-overview.svelte";

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

	async function proceedToCheckout() {
		await flightTicketVM.cacheTicketAndGotoCheckout(data.id);
	}
</script>

<div class="flex flex-col md:flex-row">
	<TicketDetailsModal {data} onCheckoutBtnClick={proceedToCheckout}>
		<Dialog.Trigger
			class={cn(
				"flex w-full flex-col justify-center gap-4 rounded-lg border-x-0 border-t-2 border-gray-200 bg-white p-6 shadow-md hover:bg-gray-50 md:border-y-2 md:border-l-2 md:border-r-2",
				TRANSITION_ALL,
			)}
		>
			<TicketLegsOverview {data} />
			<div class="flex items-center gap-2"></div>
		</Dialog.Trigger>
	</TicketDetailsModal>

	<div
		class={cn(
			"flex w-full flex-col items-center justify-center gap-4 rounded-lg border-x-0 border-b-2 border-gray-200 bg-white p-6 shadow-md md:max-w-xs md:border-y-2 md:border-l-0 md:border-r-2",
			TRANSITION_ALL,
		)}
	>
		<!-- Add price comparison logic here -->
		{#if data.priceDetails.basePrice !== data.priceDetails.displayPrice}
			{@const discountPercentage = Math.round(
				(1 -
					data.priceDetails.displayPrice /
						data.priceDetails.basePrice) *
					100,
			)}
			<div class="flex flex-col items-center gap-1">
				<Badge variant="destructive">
					<span>{discountPercentage}% OFF</span>
				</Badge>
				<div class="text-gray-500 line-through">
					{convertAndFormatCurrency(data.priceDetails.basePrice)}
				</div>
				<Title center size="h4" weight="medium" color="black">
					{convertAndFormatCurrency(data.priceDetails.displayPrice)}
				</Title>
			</div>
		{:else}
			<Title center size="h4" weight="medium" color="black">
				{convertAndFormatCurrency(data.priceDetails.displayPrice)}
			</Title>
		{/if}

		<div class="flex w-full flex-col gap-1">
			<TicketDetailsModal {data} onCheckoutBtnClick={proceedToCheckout}>
				<Dialog.Trigger
					class={cn(buttonVariants({ variant: "secondary" }))}
				>
					Flight Info
				</Dialog.Trigger>
			</TicketDetailsModal>
			<Button onclick={() => proceedToCheckout()}>Checkout</Button>
		</div>
	</div>
</div>
