<script lang="ts">
	import { page } from '$app/stores';
	import { authStore } from '$lib/stores/auth.svelte';
	import { Button } from '$lib/components/ui/button';
	import * as Card from '$lib/components/ui/card';
	import { Skeleton } from '$lib/components/ui/skeleton';
	import { toast } from 'svelte-sonner';
	import { SvelteDate } from 'svelte/reactivity';

	// Types
	type Service = {
		id: string;
		service_name: string;
		price: number;
		duration_minutes: number;
		override_price?: number;
	};

	type Booking = {
		id: string;
		start_time: string;
		status: string;
		services: Service[];
		deposit_required: boolean;
		deposit_amount?: number;
		deposit_deadline?: string;
		duration_minutes: number;
	};

	type PaymentSummary = {
		total_amount: number;
		paid_amount: number;
		refunded_amount: number;
		remaining_amount: number;
		total_vat_amount: number;
		total_net_amount: number;
		payments: Array<{
			id: string;
			status: string;
			amount: number;
			payment_type: string;
		}>;
		refunds: Array<{
			id: string;
			status: string;
			amount: number;
		}>;
	};

	// State
	let booking = $state<Booking | null>(null);
	let paymentSummary = $state<PaymentSummary | null>(null);
	let loading = $state(true);
	let error = $state<string | null>(null);

	// Get booking ID from URL
	const bookingId = $derived($page.params.id);

	// Derived values
	const totalDuration = $derived(
		booking?.services?.reduce((sum, s) => sum + s.duration_minutes, 0) ?? 0
	);

	const totalPrice = $derived(booking?.services?.reduce((sum, s) => sum + s.price, 0) ?? 0);

	const hasPaidDeposit = $derived(() => {
		if (!paymentSummary?.payments) return false;
		return paymentSummary.payments.some(
			(p) => p.status === 'completed' && (p.payment_type === 'deposit' || p.payment_type === 'full')
		);
	});

	const hasPaidAnything = $derived(() => {
		if (!paymentSummary?.payments) return false;
		return paymentSummary.payments.some((p) => p.status === 'completed');
	});

	// Format functions
	function formatDate(dateStr: string): string {
		const date = new SvelteDate(dateStr);
		return date.toLocaleDateString('en-GB', {
			weekday: 'long',
			day: 'numeric',
			month: 'long',
			year: 'numeric'
		});
	}

	function formatTime(dateStr: string): string {
		const date = new SvelteDate(dateStr);
		return date.toLocaleTimeString('en-GB', {
			hour: 'numeric',
			minute: '2-digit'
		});
	}

	function formatDuration(minutes: number): string {
		const hours = Math.floor(minutes / 60);
		const remainingMinutes = minutes % 60;

		if (hours === 0) {
			return `${remainingMinutes} minutes`;
		} else if (remainingMinutes === 0) {
			return `${hours} ${hours === 1 ? 'hour' : 'hours'}`;
		} else {
			return `${hours} ${hours === 1 ? 'hour' : 'hours'} ${remainingMinutes} minutes`;
		}
	}

	function formatPounds(pounds: number): string {
		return `£${pounds.toFixed(2)}`;
	}

	function formatPence(pence: number): string {
		return `£${(pence / 100).toFixed(2)}`;
	}

	function formatDeadline(dateStr: string): string {
		const date = new SvelteDate(dateStr);
		return date.toLocaleDateString('en-GB', {
			day: 'numeric',
			month: 'short',
			hour: 'numeric',
			minute: '2-digit'
		});
	}

	// Fetch data
	async function fetchBookingData() {
		loading = true;
		error = null;

		try {
			// Fetch booking details
			const bookingResponse = await fetch(`/api/bookings/${bookingId}`, {
				headers: {
					Authorization: `Bearer ${authStore.currentToken}`
				}
			});

			if (!bookingResponse.ok) {
				if (bookingResponse.status === 404) {
					throw new Error('Booking not found');
				}
				throw new Error('Failed to load booking');
			}

			booking = await bookingResponse.json();

			// Fetch payment summary
			const paymentResponse = await fetch(`/api/bookings/${bookingId}/payment-summary`, {
				headers: {
					Authorization: `Bearer ${authStore.currentToken}`
				}
			});

			if (paymentResponse.ok) {
				paymentSummary = await paymentResponse.json();
			}
		} catch (err) {
			error = err instanceof Error ? err.message : 'An error occurred';
			toast.error(error);
		} finally {
			loading = false;
		}
	}

	// Initialize
	$effect(() => {
		if (bookingId) {
			fetchBookingData();
		}
	});
</script>

<svelte:head>
	<title>Booking Confirmed - Crussell</title>
</svelte:head>

<div class="mx-auto max-w-2xl p-6">
	{#if loading}
		<div class="space-y-6">
			<div class="text-center">
				<Skeleton class="mx-auto h-12 w-64" />
				<Skeleton class="mx-auto mt-2 h-6 w-48" />
			</div>
			<Card.Root>
				<Card.Content class="space-y-4 pt-6">
					<Skeleton class="h-8 w-full" />
					<Skeleton class="h-20 w-full" />
					<Skeleton class="h-16 w-full" />
				</Card.Content>
			</Card.Root>
		</div>
	{:else if error}
		<Card.Root>
			<Card.Header>
				<Card.Title class="text-red-600">Error</Card.Title>
			</Card.Header>
			<Card.Content>
				<p class="text-gray-600">{error}</p>
				<Button class="mt-4" onclick={() => (window.location.href = '/')}>Return Home</Button>
			</Card.Content>
		</Card.Root>
	{:else if booking}
		<div class="mb-8 text-center">
			<div
				class="mx-auto mb-4 flex h-20 w-20 items-center justify-center rounded-full bg-green-100"
			>
				<svg
					class="h-10 w-10 text-green-600"
					viewBox="0 0 24 24"
					fill="none"
					stroke="currentColor"
					stroke-width="2"
				>
					<path d="M20 6L9 17l-5-5" stroke-linecap="round" stroke-linejoin="round" />
				</svg>
			</div>
			<h1 class="text-3xl font-bold text-gray-900">Booking Confirmed!</h1>
			<p class="mt-2 text-gray-600">Your appointment has been successfully booked</p>
		</div>

		<Card.Root class="mb-6">
			<Card.Header>
				<Card.Title>Appointment Details</Card.Title>
			</Card.Header>
			<Card.Content class="space-y-4">
				<div class="flex items-center justify-between border-b pb-4">
					<div>
						<div class="text-sm font-medium text-gray-500">Date</div>
						<div class="text-lg font-semibold">{formatDate(booking.start_time)}</div>
					</div>
					<div class="text-right">
						<div class="text-sm font-medium text-gray-500">Time</div>
						<div class="text-lg font-semibold">{formatTime(booking.start_time)}</div>
					</div>
				</div>

				<div class="flex items-center justify-between border-b pb-4">
					<div class="text-sm font-medium text-gray-500">Estimated Duration</div>
					<div class="font-semibold">{formatDuration(totalDuration)}</div>
				</div>

				<div>
					<div class="mb-3 text-sm font-medium text-gray-500">Services</div>
					<div class="space-y-2">
						{#each booking.services as service (service.id)}
							<div class="flex justify-between rounded bg-gray-50 p-3">
								<div>
									<div class="font-medium">{service.service_name}</div>
									<div class="text-sm text-gray-500">
										{service.duration_minutes} mins
									</div>
								</div>
								<div class="font-semibold">
									{formatPounds(service.price)}
								</div>
							</div>
						{/each}
					</div>
				</div>

				<div class="flex justify-between border-t pt-4">
					<div class="text-lg font-semibold">Total</div>
					<div class="text-lg font-bold">{formatPounds(totalPrice)}</div>
				</div>
			</Card.Content>
		</Card.Root>

		<Card.Root>
			<Card.Header>
				<Card.Title>Payment</Card.Title>
			</Card.Header>
			<Card.Content>
				{#if booking.deposit_required}
					{#if hasPaidDeposit()}
						<div class="flex items-center gap-3 rounded-lg border border-green-200 bg-green-50 p-4">
							<svg
								class="h-6 w-6 text-green-600"
								viewBox="0 0 24 24"
								fill="none"
								stroke="currentColor"
								stroke-width="2"
							>
								<path d="M20 6L9 17l-5-5" stroke-linecap="round" stroke-linejoin="round" />
							</svg>
							<div>
								<div class="font-semibold text-green-800">Deposit Paid</div>
								<div class="text-sm text-green-700">
									Your deposit of {formatPounds(booking.deposit_amount ?? 0)} has been paid
								</div>
							</div>
						</div>
						{#if paymentSummary && paymentSummary.remaining_amount > 0}
							<div class="mt-4 rounded-lg bg-gray-50 p-4">
								<div class="flex justify-between">
									<span class="text-gray-600">Remaining Balance</span>
									<span class="font-semibold">{formatPence(paymentSummary.remaining_amount)}</span>
								</div>
								<p class="mt-2 text-sm text-gray-500">
									You can pay the remaining balance on the day of your appointment
								</p>
							</div>
						{/if}
					{:else}
						<div class="space-y-4">
							<div class="rounded-lg border border-amber-200 bg-amber-50 p-4">
								<div class="flex items-center justify-between">
									<div>
										<div class="font-semibold text-amber-800">Deposit Required</div>
										<div class="text-sm text-amber-700">
											To secure your booking, please pay a deposit of {formatPounds(
												booking.deposit_amount ?? 0
											)}
										</div>
									</div>
									<div class="text-2xl font-bold text-amber-800">
										{formatPounds(booking.deposit_amount ?? 0)}
									</div>
								</div>
								{#if booking.deposit_deadline}
									<div class="mt-2 text-sm text-amber-600">
										Please pay before {formatDeadline(booking.deposit_deadline)}
									</div>
								{/if}
							</div>

							<Button class="w-full" onclick={() => toast.info('Payment integration coming soon')}>
								Pay Deposit Now
							</Button>
						</div>
					{/if}
				{:else}
					<div class="space-y-4">
						<div class="rounded-lg bg-gray-50 p-4">
							<p class="text-gray-600">
								You can pay on the day, but if you'd prefer you can pay ahead here
							</p>
						</div>

						{#if hasPaidAnything()}
							<div
								class="flex items-center gap-3 rounded-lg border border-green-200 bg-green-50 p-4"
							>
								<svg
									class="h-6 w-6 text-green-600"
									viewBox="0 0 24 24"
									fill="none"
									stroke="currentColor"
									stroke-width="2"
								>
									<path d="M20 6L9 17l-5-5" stroke-linecap="round" stroke-linejoin="round" />
								</svg>
								<div>
									<div class="font-semibold text-green-800">Paid</div>
									<div class="text-sm text-green-700">
										{formatPence(paymentSummary?.paid_amount ?? 0)} paid
									</div>
								</div>
							</div>
							{#if paymentSummary && paymentSummary.total_vat_amount > 0}
								<div class="mt-2 rounded-lg bg-gray-50 p-3">
									<div class="flex justify-between text-sm">
										<span class="text-gray-600">Net amount</span>
										<span class="font-medium">{formatPence(paymentSummary.total_net_amount)}</span>
									</div>
									<div class="flex justify-between text-sm">
										<span class="text-gray-600">VAT</span>
										<span class="font-medium">{formatPence(paymentSummary.total_vat_amount)}</span>
									</div>
									<div
										class="mt-1 flex justify-between border-t border-gray-200 pt-1 text-sm font-semibold"
									>
										<span class="text-gray-800">Total paid</span>
										<span class="text-gray-800">{formatPence(paymentSummary.paid_amount)}</span>
									</div>
								</div>
							{/if}
						{:else}
							<Button class="w-full" onclick={() => toast.info('Payment integration coming soon')}>
								Pay Now
							</Button>
						{/if}
					</div>
				{/if}
			</Card.Content>
		</Card.Root>

		<div class="mt-6 flex flex-col gap-4 sm:flex-row sm:justify-center">
			<Button variant="outline" onclick={() => (window.location.href = '/schedule')}>
				View My Bookings
			</Button>
			<Button variant="ghost" onclick={() => (window.location.href = '/')}>Return Home</Button>
		</div>
	{/if}
</div>
