<script lang="ts">
	import Title from "$lib/components/atoms/title.svelte";
	import {
		convertAndFormatCurrency,
		currencyStore,
	} from "$lib/domains/currency/view/currency.vm.svelte";
	import { customerInfoVM } from "../customerinfo/view/customerinfo.vm.svelte";
	import { productStore } from "../product/store";
	import { calculateFinalPrices } from "./utils";

	let priceDetails = $state(
		calculateFinalPrices($productStore, customerInfoVM.customerInfo),
	);
	let calculating = $state(false);

	// Reactively update price details when product or customer info changes
	$effect(() => {
		calculating = true;
		priceDetails = calculateFinalPrices(
			$productStore,
			customerInfoVM.customerInfo,
		);
		calculating = false;
	});
</script>

<div class="flex flex-col gap-4 rounded-lg bg-white p-4 drop-shadow-lg md:p-8">
	<Title size="h4" weight="medium">Payment Summary</Title>
	<div class="h-0.5 w-full border-t-2 border-gray-200"></div>

	{#if !calculating}
		<!-- Product Information -->
		{#if $productStore}
			<div class="flex flex-col gap-2">
				<Title size="p" weight="medium">{$productStore.title}</Title>
				<p class="text-sm text-gray-600">{$productStore.description}</p>
			</div>
		{/if}

		<!-- Price Breakdown -->
		<div class="mt-2 flex flex-col gap-2 border-t pt-4">
			<div class="flex justify-between text-sm">
				<span>Base Price</span>
				<span>{convertAndFormatCurrency(priceDetails.basePrice)}</span>
			</div>

			{#if priceDetails.discountAmount > 0}
				<div class="flex justify-between text-sm text-green-600">
					<span>Discount</span>
					<span
						>-{convertAndFormatCurrency(
							priceDetails.discountAmount,
						)}</span
					>
				</div>
				<div class="flex justify-between text-sm">
					<span>Display Price</span>
					<span
						>{convertAndFormatCurrency(
							priceDetails.displayPrice,
						)}</span
					>
				</div>
			{/if}
		</div>

		<!-- Final Total -->
		<div class="mt-4 flex flex-col gap-2 border-t pt-4">
			<div class="flex justify-between font-medium">
				<Title size="h5" weight="medium"
					>Total ({$currencyStore.code})</Title
				>
				<span class="text-lg"
					>{convertAndFormatCurrency(priceDetails.orderPrice)}</span
				>
			</div>
		</div>
	{:else}
		<div class="grid place-items-center p-8 text-center">
			<span class="text-gray-600">Calculating...</span>
		</div>
	{/if}

	<!-- Important Information -->
	<div class="mt-4 rounded-lg bg-gray-50 p-4 text-xs text-gray-600">
		<p class="mb-2 font-medium">Important Information:</p>
		<ul class="list-disc space-y-1 pl-4">
			<li>Price includes all applicable taxes and fees</li>
			<li>
				Cancellation and refund policies may apply as per our terms of
				service
			</li>
			<li>Payment will be processed securely upon order confirmation</li>
		</ul>
	</div>
</div>
