<script lang="ts">
	import { authStore } from '$lib/stores/auth.svelte';
	import { SvelteDate } from 'svelte/reactivity';
	import { toast } from 'svelte-sonner';
	import * as Modal from '$lib/components/ui/dialog';
	import { Button } from '$lib/components/ui/button';
	import ApprovalModal from '$lib/components/admin/ApprovalModal.svelte';
	import type { Booking } from '$lib/types/booking';

	interface Props {
		open: boolean;
		bookingId: string;
	}

	let { open = $bindable(), bookingId }: Props = $props();

	let selectedBooking = $state<Booking | null>(null);
	let showApprovalModal = $state(false);

	// Calculate total duration from services
	let totalDuration = $derived(
		selectedBooking?.services?.reduce((sum, service) => sum + (service.duration_minutes || 0), 0) ||
			0
	);

	async function fetchBookingDetails() {
		if (!bookingId) return;

		try {
			const response = await fetch(`/api/admin/bookings/${bookingId}`, {
				method: 'GET',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${authStore.currentToken}`
				}
			});

			if (response.ok) {
				const data = await response.json();

				selectedBooking = {
					id: data.id,
					start_time: data.start_time,
					status: data.status,
					notes: data.notes,
					created_at: data.created_at,
					updated_at: data.updated_at,
					created_by: data.created_by,

					// Deposit fields
					deposit_required: data.deposit_required ?? false,
					deposit_amount: data.deposit_amount,
					deposit_paid: data.deposit_paid ?? false,
					deposit_deadline: data.deposit_deadline,

					// User
					user: data.user
						? {
								id: data.user.id,
								first_name: data.user.first_name,
								last_name: data.user.last_name,
								full_name: data.user.full_name,
								email: data.user.email,
								phone: data.user.phone,
								profile_pic_url: data.user.profile_pic_url,
								date_of_birth: data.user.date_of_birth,
								account_role: data.user.account_role,
								loyalty_stamps: data.user.loyalty_stamps,
								referral_code: data.user.referral_code,
								referral_code_uses: data.user.referral_code_uses,
								created_at: data.user.created_at,
								notes: data.user.notes
							}
						: undefined,

					// Services
					services: (data.services || []).map((s) => ({
						booking_id: s.booking_id,
						service_id: s.service_id,
						service_name: s.service_name,
						service_description: s.service_description,
						price: s.price,
						duration_minutes: s.duration_minutes,
						override_price: s.override_price,
						override_duration_minutes: s.override_duration_minutes
					})),

					// Payments
					payments: (data.payments || []).map((p) => ({
						id: p.id,
						booking_id: p.booking_id,
						payment_type: p.payment_type,
						payment_method: p.payment_method,
						vendor_code: p.vendor_code,
						invoice_number: p.invoice_number,
						status: p.status,
						amount: p.amount,
						is_vat_applicable: p.is_vat_applicable,
						vat_rate: p.vat_rate,
						vat_amount: p.vat_amount,
						net_amount: p.net_amount,
						created_at: p.created_at,
						updated_at: p.updated_at,
						created_by: p.created_by
					})),

					// Financials
					total_amount: data.total_amount || 0,
					amount_paid: data.amount_paid || 0,
					amount_due: data.amount_due || 0,
					duration_minutes: data.duration_minutes || 0
				};
			} else {
				const text = await response.text();
				toast.error('Failed to load booking details: ' + text);
			}
		} catch (err) {
			console.error('Error fetching booking details:', err);
			toast.error('Network error loading booking details');
		}
	}

	$effect(() => {
		if (open && bookingId) {
			fetchBookingDetails();
		}
	});
</script>

<Modal.Root bind:open>
	<Modal.Content class="max-h-[90vh] max-w-sm overflow-y-auto md:max-w-3xl">
		<Modal.Header>
			<div class="flex items-center justify-between">
				<div>
					<Modal.Title class="text-lg font-semibold">Booking Details</Modal.Title>
					{#if selectedBooking}
						<div class="mt-1 text-sm text-gray-500">ID: {selectedBooking.id}</div>
					{/if}
				</div>
				{#if selectedBooking}
					{@const isConfirmedOrLater = ['confirmed', 'in_progress', 'completed'].includes(selectedBooking.status)}

					{#if selectedBooking.status === 'pending'}
						<div class="flex items-center gap-2">
							<Button
								onclick={() => (showApprovalModal = true)}
								class="bg-emerald-600 hover:bg-emerald-700"
							>
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="mr-2 h-4 w-4"
									viewBox="0 0 20 20"
									fill="currentColor"
								>
									<path
										fill-rule="evenodd"
										d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
										clip-rule="evenodd"
									/>
								</svg>
								Approve Booking
							</Button>

							<span
								class="inline-flex items-center rounded-full bg-yellow-100 px-3 py-1 text-sm
								font-medium text-yellow-800"
							>
								Pending
							</span>

						<!-- Deposit Badge for pending -->
						{#if selectedBooking.deposit_required}
							<span
								class="inline-flex items-center rounded-full bg-blue-100 px-3 py-1 text-sm font-medium text-blue-800"
							>
								Will Require Deposit
							</span>
						{/if}
						</div>
					{:else if isConfirmedOrLater && selectedBooking.deposit_required}
						<!-- Deposit Badge for confirmed+ -->
						<div class="flex items-center gap-2">
							<span
								class="inline-flex items-center rounded-full px-3 py-1 text-sm font-medium
								{selectedBooking.status === 'completed'
									? 'bg-green-100 text-green-800'
									: selectedBooking.status === 'in_progress'
										? 'bg-blue-100 text-blue-800'
										: 'bg-emerald-100 text-emerald-800'}"
							>
								{selectedBooking.status.replace('_', ' ')}
							</span>
						<span
							class="inline-flex items-center rounded-full px-3 py-1 text-sm font-medium
							{selectedBooking.deposit_paid
								? 'bg-green-100 text-green-800'
								: 'bg-orange-100 text-orange-800'}"
						>
							{selectedBooking.deposit_paid ? 'Deposit Paid' : 'Deposit Due'}
						</span>
						</div>
					{/if}
				{/if}
			</div>
		</Modal.Header>

		{#if selectedBooking}
			<div class="space-y-6 px-4 pb-4">
				<!-- Appointment Details -->
				<div class="rounded-lg border border-gray-200 bg-gray-50 p-4">
					<h3 class="mb-3 text-sm font-semibold tracking-wide text-gray-600 uppercase">
						Appointment Details
					</h3>
					<div class="grid gap-3 md:grid-cols-2">
						<div>
							<div class="text-xs text-gray-500">Scheduled Date & Time</div>
							<div class="font-medium">
								{(() => {
									const date = new SvelteDate(selectedBooking.start_time);
									const dateStr = date.toLocaleDateString('en-US', {
										weekday: 'long',
										day: 'numeric',
										month: 'short'
									});
									const timeStr = date.toLocaleTimeString('en-US', {
										hour: 'numeric',
										minute: '2-digit',
										hour12: true
									});
									return `${dateStr} at ${timeStr}`;
								})()}
							</div>
						</div>
						<div>
							<div class="text-xs text-gray-500">Duration</div>
							<div class="font-medium">{totalDuration} minutes</div>
						</div>
						<div>
							<div class="text-xs text-gray-500">Created</div>
							<div class="text-sm">
								{new SvelteDate(selectedBooking.created_at).toLocaleString()}
							</div>
						</div>
						<div>
							<div class="text-xs text-gray-500">Last Updated</div>
							<div class="text-sm">
								{new SvelteDate(selectedBooking.updated_at).toLocaleString()}
							</div>
						</div>
						{#if selectedBooking.created_by}
							<div class="md:col-span-2">
								<div class="text-xs text-gray-500">Created By</div>
								<div class="text-sm">{selectedBooking.created_by}</div>
							</div>
						{/if}
					</div>
					{#if selectedBooking.notes}
						<div class="mt-3 rounded-md border border-amber-200 bg-amber-50 p-3">
							<div class="mb-1 text-xs font-semibold text-amber-800">Booking Notes</div>
							<div class="text-sm text-amber-900">{selectedBooking.notes}</div>
						</div>
					{/if}
				</div>

				<!-- Deposit Info (moved to Financial Summary) -->

				<!-- Services -->
				{#if selectedBooking.services && selectedBooking.services.length > 0}
					<div class="rounded-lg border border-gray-200 bg-gray-50 p-4">
						<h3 class="mb-3 text-sm font-semibold tracking-wide text-gray-600 uppercase">
							Services
						</h3>
						<div class="space-y-3">
							{#each selectedBooking.services as service, index (index)}
								<div class="rounded-md border border-gray-300 bg-white p-3">
									<div class="font-medium">{service.service_name || '—'}</div>
									{#if service.service_description}
										<div class="mt-1 text-sm text-gray-600">{service.service_description}</div>
									{/if}
									<div class="mt-2 flex items-center justify-between text-sm">
										<span class="text-gray-600">{service.duration_minutes} min</span>
										<span class="font-semibold">£{service.price?.toFixed(2) || '0.00'}</span>
									</div>
								</div>
							{/each}
						</div>
					</div>
				{/if}

				<!-- Customer Information -->
				<div class="rounded-lg border border-gray-200 bg-gray-50 p-4">
					<h3 class="mb-3 text-sm font-semibold tracking-wide text-gray-600 uppercase">
						Customer Information
					</h3>
					<div class="grid gap-3 md:grid-cols-2">
						<div>
							<div class="text-xs text-gray-500">Name</div>
							<div class="font-medium">{selectedBooking.user?.full_name || '—'}</div>
						</div>
						<div>
							<div class="text-xs text-gray-500">Email</div>
							<div class="font-medium break-all">{selectedBooking.user?.email || '—'}</div>
						</div>
						<div>
							<div class="text-xs text-gray-500">Phone</div>
							<div class="font-medium">{selectedBooking.user?.phone || '—'}</div>
						</div>
						<div>
							<div class="text-xs text-gray-500">Customer ID</div>
							<div class="font-medium">{selectedBooking.user?.id || '—'}</div>
						</div>
						{#if selectedBooking.user?.loyalty_stamps !== undefined && selectedBooking.user?.loyalty_stamps !== null}
							<div>
								<div class="text-xs text-gray-500">Loyalty Stamps</div>
								<div class="font-medium">{selectedBooking.user.loyalty_stamps}</div>
							</div>
						{/if}
						{#if selectedBooking.user?.referral_code}
							<div>
								<div class="text-xs text-gray-500">Referral Code</div>
								<div class="font-medium">{selectedBooking.user.referral_code}</div>
							</div>
						{/if}
						{#if selectedBooking.user?.referral_code_uses !== undefined && selectedBooking.user?.referral_code_uses !== null}
							<div>
								<div class="text-xs text-gray-500">Referral Uses</div>
								<div class="font-medium">{selectedBooking.user.referral_code_uses}</div>
							</div>
						{/if}
					</div>
					{#if selectedBooking.user?.notes}
						<div class="mt-3 rounded-md border border-blue-200 bg-blue-50 p-3">
							<div class="mb-1 text-xs font-semibold text-blue-800">Customer Notes</div>
							<div class="text-sm text-blue-900">{selectedBooking.user.notes}</div>
						</div>
					{/if}
				</div>

				<!-- Financial Summary -->
				<div class="rounded-lg border border-gray-200 bg-gray-50 p-4">
					<h3 class="mb-3 text-sm font-semibold tracking-wide text-gray-600 uppercase">
						Financial Summary
					</h3>
						<div class="space-y-2">
							{#if ['confirmed', 'in_progress', 'completed'].includes(selectedBooking.status) && selectedBooking.deposit_required}
								<!-- Deposit Info -->
								<div class="flex items-center justify-between border-b border-gray-200 pb-2">
									<span class="text-sm text-gray-600">Deposit Required</span>
									<div class="text-right">
										<div class="font-semibold">£{selectedBooking.deposit_amount?.toFixed(2) || '0.00'}</div>
										<div class="text-xs">
											<span
												class="{selectedBooking.deposit_paid
													? 'text-green-600'
													: 'text-orange-600'}"
											>
												{selectedBooking.deposit_paid ? 'Paid' : 'Outstanding'}
											</span>
											{#if !selectedBooking.deposit_paid && selectedBooking.deposit_deadline}
												<span class="text-gray-500">
													• Due: {new SvelteDate(selectedBooking.deposit_deadline).toLocaleDateString('en-GB', {
														weekday: 'short',
														day: 'numeric',
														month: 'short',
														year: 'numeric'
													})} at {new SvelteDate(selectedBooking.deposit_deadline).toLocaleTimeString('en-GB', {
														hour: 'numeric',
														minute: '2-digit',
														hour12: true
													})}
												</span>
											{/if}
										</div>
									</div>
								</div>
							{/if}

						<div class="flex items-center justify-between">
							<span class="text-sm text-gray-600">Total Amount</span>
							<span class="font-semibold">£{selectedBooking.total_amount.toFixed(2)}</span>
						</div>
						<div class="flex items-center justify-between">
							<span class="text-sm text-gray-600">Amount Paid</span>
							<span class="font-semibold text-green-700"
								>£{selectedBooking.amount_paid.toFixed(2)}</span
							>
						</div>
						<div class="flex items-center justify-between border-t border-gray-300 pt-2">
							<span class="font-medium text-gray-900">Amount Due</span>
							<span
								class="text-lg font-bold {selectedBooking.amount_due > 0
									? 'text-red-600'
									: 'text-green-600'}"
							>
								£{selectedBooking.amount_due.toFixed(2)}
							</span>
						</div>
					</div>
				</div>

				<!-- Payments -->
				{#if selectedBooking.payments && selectedBooking.payments.length > 0}
					<div class="rounded-lg border border-gray-200 bg-gray-50 p-4">
						<h3 class="mb-3 text-sm font-semibold tracking-wide text-gray-600 uppercase">
							Payment History
						</h3>
						<div class="space-y-3">
							{#each selectedBooking.payments as payment (payment.id)}
								<div class="rounded-md border border-gray-300 bg-white p-3">
									<div class="flex items-start justify-between">
										<div class="flex-1">
											<div class="flex items-center gap-2">
												<span class="font-medium capitalize"
													>{payment.payment_method.replace('_', ' ')}</span
												>
												<span
													class="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium
											{payment.status === 'completed'
														? 'bg-green-100 text-green-800'
														: payment.status === 'pending'
															? 'bg-yellow-100 text-yellow-800'
															: payment.status === 'failed'
																? 'bg-red-100 text-red-800'
																: 'bg-gray-100 text-gray-800'}"
												>
													{payment.status}
												</span>
											</div>
											<div class="mt-1 text-xs text-gray-500">
												{payment.payment_type.charAt(0).toUpperCase() +
													payment.payment_type.slice(1)}
											</div>
											{#if payment.vendor_code || payment.invoice_number}
												<div class="mt-1 text-xs text-gray-500">
													{#if payment.vendor_code}Vendor: {payment.vendor_code}{/if}
													{#if payment.vendor_code && payment.invoice_number}
														•
													{/if}
													{#if payment.invoice_number}Invoice: #{payment.invoice_number}{/if}
												</div>
											{/if}
											{#if payment.is_vat_applicable}
												<div class="mt-2 text-xs text-gray-600">
													<div>Net: £{payment.net_amount?.toFixed(2) || '0.00'}</div>
													<div>
														VAT ({(payment.vat_rate || 0) * 100}%): £{payment.vat_amount?.toFixed(
															2
														) || '0.00'}
													</div>
												</div>
											{/if}
											<div class="mt-1 text-xs text-gray-400">
												{new SvelteDate(payment.created_at).toLocaleString()}
											</div>
										</div>
										<div class="text-right font-semibold">
											£{payment.amount.toFixed(2)}
										</div>
									</div>
								</div>
							{/each}
						</div>
					</div>
				{/if}
			</div>
		{/if}

		<Modal.Footer class="flex items-center justify-end gap-2">
			<Button onclick={() => (open = false)}>Close</Button>
		</Modal.Footer>
	</Modal.Content>
</Modal.Root>

<!-- Approval Sub-Modal -->
{#if selectedBooking && showApprovalModal}
	<ApprovalModal
		bind:open={showApprovalModal}
		booking={selectedBooking}
		onApproved={() => {
			showApprovalModal = false;
			fetchBookingDetails();
		}}
	/>
{/if}
