<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import AdminPageHeader from '$lib/components/admin/AdminPageHeader.svelte';
	import WaveInvoiceEditForm from '$lib/components/admin/invoices/wave/WaveInvoiceEditForm.svelte';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';
	import { SvelteDate } from 'svelte/reactivity';
	import { enhance } from '$app/forms';
	import { goto, invalidateAll } from '$app/navigation';
	import type { PageData } from './$types';

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

	let invoice = $derived(data.invoice);
	let waveProducts = $derived(data.waveProducts);

	// Edit mode state
	let isEditing = $state(false);
	let isSending = $state(false);
	let isApproving = $state(false);
	let isDeleting = $state(false);
	let sendFormRef = $state<HTMLFormElement | null>(null);
	let approveFormRef = $state<HTMLFormElement | null>(null);
	let deleteFormRef = $state<HTMLFormElement | null>(null);

	// Can edit DRAFT or SAVED invoices
	let canEdit = $derived(invoice.status === 'DRAFT' || invoice.status === 'SAVED');
	let canApprove = $derived(invoice.status === 'DRAFT');
	let canSend = $derived(invoice.status === 'SAVED');
	let canDelete = $derived(invoice.status === 'DRAFT' || invoice.status === 'SAVED');

	function handleEdit() {
		isEditing = true;
	}

	async function handleEditSuccess() {
		isEditing = false;
		await invalidateAll();
	}

	function handleEditCancel() {
		isEditing = false;
	}

	function handleSend() {
		sendFormRef?.requestSubmit();
	}

	function handleApprove() {
		approveFormRef?.requestSubmit();
	}

	function handleDelete() {
		if (confirm('Are you sure you want to delete this Wave invoice? This cannot be undone.')) {
			deleteFormRef?.requestSubmit();
		}
	}

	// Convert standalone page invoice format to WaveInvoice format for the edit form
	let waveInvoiceForEdit = $derived({
		id: invoice.id,
		invoiceNumber: invoice.invoiceNumber,
		invoiceDate: invoice.invoiceDate,
		dueDate: invoice.dueDate,
		status: invoice.status,
		title: invoice.title ?? '',
		subhead: invoice.subhead,
		poNumber: invoice.poNumber,
		memo: invoice.memo,
		footer: invoice.footer,
		pdfUrl: invoice.pdfUrl ?? '',
		viewUrl: invoice.viewUrl ?? '',
		customer: {
			id: invoice.customer.id,
			name: invoice.customer.name,
			email: invoice.customer.email
		},
		items: invoice.items.map((item) => ({
			product: {
				id: item.product?.id ?? '',
				name: item.product?.name ?? ''
			},
			description: item.description,
			quantity: parseFloat(item.quantity),
			unitPrice: parseFloat(item.unitPrice),
			subtotal: item.subtotal,
			total: item.total
		})),
		subtotal: invoice.subtotal,
		taxTotal: invoice.taxTotal,
		discountTotal: invoice.discountTotal,
		total: invoice.total,
		amountDue: invoice.amountDue,
		amountPaid: invoice.amountPaid,
		lastSentAt: invoice.lastSentAt,
		lastSentVia: invoice.lastSentVia,
		lastViewedAt: invoice.lastViewedAt
	});

	// Format date for display
	function formatDate(dateStr: string | null): string {
		if (!dateStr) return '—';
		return new Date(dateStr + 'T00:00:00').toLocaleDateString('en-US', {
			month: 'long',
			day: 'numeric',
			year: 'numeric'
		});
	}

	function formatShortDate(dateStr: string | null): string {
		if (!dateStr) return '—';
		return new Date(dateStr + 'T00:00:00').toLocaleDateString('en-US', {
			month: 'short',
			day: 'numeric',
			year: 'numeric'
		});
	}

	function formatDateTime(dateStr: string | null): string {
		if (!dateStr) return '—';
		return new Date(dateStr).toLocaleDateString('en-US', {
			month: 'short',
			day: 'numeric',
			year: 'numeric',
			hour: 'numeric',
			minute: '2-digit'
		});
	}

	// Format currency
	function formatCurrency(value: string | number | null | undefined, symbol: string = '$'): string {
		if (value === null || value === undefined) return `${symbol}0.00`;
		// Remove commas before parsing (Wave API may return formatted strings)
		const num = typeof value === 'string' ? parseFloat(value.replace(/,/g, '')) : value;
		return `${symbol}${num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
	}

	// Get status badge classes
	function getStatusClasses(status: string): string {
		switch (status) {
			case 'DRAFT':
				return 'bg-gray-500/10 text-gray-600 dark:text-gray-400';
			case 'SAVED':
				return 'bg-gray-500/10 text-gray-600 dark:text-gray-400';
			case 'SENT':
				return 'bg-primary-500/10 text-primary-600 dark:text-primary-400';
			case 'VIEWED':
				return 'bg-accent2-500/10 text-accent2-600 dark:text-accent2-400';
			case 'PAID':
				return 'bg-success-500/10 text-success-600 dark:text-success-400';
			case 'PARTIAL':
				return 'bg-warning-500/10 text-warning-600 dark:text-warning-400';
			case 'OVERDUE':
				return 'bg-error-500/10 text-error-600 dark:text-error-400';
			default:
				return 'bg-gray-500/10 text-gray-600 dark:text-gray-400';
		}
	}

	// Get status display label
	function getStatusLabel(status: string): string {
		switch (status) {
			case 'DRAFT':
				return 'Draft';
			case 'SAVED':
				return 'Saved';
			case 'SENT':
				return 'Sent';
			case 'VIEWED':
				return 'Viewed';
			case 'PAID':
				return 'Paid';
			case 'PARTIAL':
				return 'Partial';
			case 'OVERDUE':
				return 'Overdue';
			default:
				return status;
		}
	}

	// Check if invoice is overdue
	function isOverdue(dueDate: string, status: string): boolean {
		if (status === 'PAID') return false;
		const due = new Date(dueDate + 'T00:00:00');
		const today = new SvelteDate();
		today.setHours(0, 0, 0, 0);
		return due < today;
	}

	// Format customer address
	function formatAddress(
		address: {
			addressLine1: string | null;
			addressLine2: string | null;
			city: string | null;
			province: { code: string; name: string } | null;
			country: { code: string; name: string } | null;
			postalCode: string | null;
		} | null
	): string[] {
		if (!address) return [];
		const lines: string[] = [];
		if (address.addressLine1) lines.push(address.addressLine1);
		if (address.addressLine2) lines.push(address.addressLine2);
		const cityLine: string[] = [];
		if (address.city) cityLine.push(address.city);
		if (address.province?.code) cityLine.push(address.province.code);
		if (address.postalCode) cityLine.push(address.postalCode);
		if (cityLine.length > 0) lines.push(cityLine.join(', '));
		if (address.country?.name) lines.push(address.country.name);
		return lines;
	}

	let overdue = $derived(isOverdue(invoice.dueDate, invoice.status));
	let addressLines = $derived(formatAddress(invoice.customer.address));
</script>

<svelte:head>
	<title>Invoice #{invoice.invoiceNumber} - Wave - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<AdminPageHeader
			title={invoice.customer.name}
			subtitle="Invoice #{invoice.invoiceNumber}"
			colorScheme="accent6"
			backHref="/admin/invoices/wave"
		/>

		<!-- Hidden form for approving Wave invoice -->
		<form
			bind:this={approveFormRef}
			method="POST"
			action="?/approveWaveInvoice"
			use:enhance={() => {
				isApproving = true;
				return async ({ result }) => {
					isApproving = false;
					if (result.type === 'failure') {
						const errorMsg = result.data?.error;
						alert(typeof errorMsg === 'string' ? errorMsg : 'Failed to approve invoice');
					} else if (result.type === 'success') {
						await invalidateAll();
					}
				};
			}}
			class="hidden"
		>
			<input type="hidden" name="invoiceId" value={invoice.id} />
		</form>

		<!-- Hidden form for sending Wave invoice -->
		<form
			bind:this={sendFormRef}
			method="POST"
			action="?/sendWaveInvoice"
			use:enhance={() => {
				isSending = true;
				return async ({ result }) => {
					isSending = false;
					if (result.type === 'failure') {
						const errorMsg = result.data?.error;
						alert(typeof errorMsg === 'string' ? errorMsg : 'Failed to send invoice');
					} else if (result.type === 'success') {
						await invalidateAll();
					}
				};
			}}
			class="hidden"
		>
			<input type="hidden" name="invoiceId" value={invoice.id} />
			<input type="hidden" name="customerEmail" value={invoice.customer.email ?? ''} />
		</form>

		<!-- Hidden form for deleting Wave invoice -->
		<form
			bind:this={deleteFormRef}
			method="POST"
			action="?/deleteWaveInvoice"
			use:enhance={() => {
				isDeleting = true;
				return async ({ result }) => {
					isDeleting = false;
					if (result.type === 'failure') {
						const errorMsg = result.data?.error;
						alert(typeof errorMsg === 'string' ? errorMsg : 'Failed to delete invoice');
					} else if (result.type === 'success') {
						await goto('/admin/invoices/wave');
					}
				};
			}}
			class="hidden"
		>
			<input type="hidden" name="invoiceId" value={invoice.id} />
		</form>

		{#if isEditing}
			<!-- Edit Mode -->
			<WaveInvoiceEditForm
				waveInvoice={waveInvoiceForEdit}
				{waveProducts}
				onSuccess={handleEditSuccess}
				onCancel={handleEditCancel}
			/>
		{:else}
			<!-- Status & Actions Card -->
			<div class="mb-6 card-padded">
				<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
					<div class="flex flex-wrap items-center gap-3">
						<span
							class={`inline-flex items-center rounded-full px-3 py-1 text-sm font-medium ${overdue && invoice.status !== 'PAID' ? 'bg-error-500/10 text-error-600 dark:text-error-400' : getStatusClasses(invoice.status)}`}
						>
							{overdue && invoice.status !== 'PAID' ? 'Overdue' : getStatusLabel(invoice.status)}
						</span>

						{#if invoice.lastViewedAt}
							<span
								class="inline-flex items-center gap-1.5 text-sm text-accent2-600 dark:text-accent2-400"
							>
								<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
									/>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
									/>
								</svg>
								Viewed
							</span>
						{/if}
					</div>

					<div class="flex flex-wrap items-center gap-2">
						{#if invoice.pdfUrl}
							<a
								href={invoice.pdfUrl}
								target="_blank"
								rel="noopener noreferrer"
								class="flex items-center gap-2 rounded-lg border border-theme interactive bg-theme px-3 py-2 text-sm font-medium text-theme"
							>
								<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
									/>
								</svg>
								Download PDF
							</a>
						{/if}

						{#if canEdit}
							<button
								type="button"
								onclick={handleEdit}
								class="flex items-center gap-2 rounded-lg border border-theme interactive bg-theme px-3 py-2 text-sm font-medium text-theme"
							>
								<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
									/>
								</svg>
								Edit
							</button>
						{/if}

						{#if canApprove}
							<button
								type="button"
								onclick={handleApprove}
								disabled={isApproving}
								class="flex items-center gap-2 rounded-lg bg-success-500 px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-success-600 disabled:cursor-not-allowed disabled:opacity-50"
							>
								{#if isApproving}
									<IconSpinner class="h-4 w-4" />
									<span>Approving...</span>
								{:else}
									<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M5 13l4 4L19 7"
										/>
									</svg>
									Approve
								{/if}
							</button>
						{/if}

						{#if canSend}
							<button
								type="button"
								onclick={handleSend}
								disabled={isSending}
								class="flex items-center gap-2 rounded-lg bg-primary-500 px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-600 disabled:cursor-not-allowed disabled:opacity-50"
							>
								{#if isSending}
									<IconSpinner class="h-4 w-4" />
									<span>Sending...</span>
								{:else}
									<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
										/>
									</svg>
									Send Invoice
								{/if}
							</button>
						{/if}

						{#if canDelete}
							<button
								type="button"
								onclick={handleDelete}
								disabled={isDeleting}
								class="flex items-center gap-2 rounded-lg bg-error-500/10 px-3 py-2 text-sm font-medium text-error-600 transition-colors hover:bg-error-500/20 disabled:cursor-not-allowed disabled:opacity-50 dark:text-error-400"
							>
								{#if isDeleting}
									<IconSpinner class="h-4 w-4" />
									<span>Deleting...</span>
								{:else}
									<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
										/>
									</svg>
									Delete
								{/if}
							</button>
						{/if}
					</div>
				</div>
			</div>

			<!-- Invoice Summary Card -->
			<div class="mb-6 card-padded">
				<h3 class="mb-4 text-sm font-medium text-theme-muted">Invoice Summary</h3>

				<div class="space-y-4">
					<!-- Subtotal -->
					<div class="flex items-center justify-between border-b border-theme py-3">
						<div class="flex items-center gap-3">
							<div
								class="flex h-10 w-10 items-center justify-center rounded-lg bg-secondary-500/20"
							>
								<svg
									class="h-5 w-5 text-secondary-600 dark:text-secondary-400"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"
									/>
								</svg>
							</div>
							<div>
								<p class="font-medium text-theme">Subtotal</p>
								<p class="text-sm text-theme-muted">
									{invoice.items.length} line item{invoice.items.length !== 1 ? 's' : ''}
								</p>
							</div>
						</div>
						<p class="text-lg font-bold text-secondary-600 dark:text-secondary-400">
							{formatCurrency(invoice.subtotal.value, invoice.subtotal.currency.symbol)}
						</p>
					</div>

					<!-- Discount (if any) -->
					{#if parseFloat(invoice.discountTotal.value) > 0}
						<div class="flex items-center justify-between border-b border-theme py-3">
							<div class="flex items-center gap-3">
								<div
									class="flex h-10 w-10 items-center justify-center rounded-lg bg-warning-500/20"
								>
									<svg
										class="h-5 w-5 text-warning-600 dark:text-warning-400"
										style="fill: none"
										stroke="currentColor"
										viewBox="0 0 24 24"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"
										/>
									</svg>
								</div>
								<div>
									<p class="font-medium text-theme">Discounts</p>
									<p class="text-sm text-theme-muted">
										{invoice.discounts.length} discount{invoice.discounts.length !== 1 ? 's' : ''}
									</p>
								</div>
							</div>
							<p class="text-lg font-bold text-warning-600 dark:text-warning-400">
								-{formatCurrency(
									invoice.discountTotal.value,
									invoice.discountTotal.currency.symbol
								)}
							</p>
						</div>
					{/if}

					<!-- Tax (if any) -->
					{#if parseFloat(invoice.taxTotal.value) > 0}
						<div class="flex items-center justify-between border-b border-theme py-3">
							<div class="flex items-center gap-3">
								<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-accent-500/20">
									<svg
										class="h-5 w-5 text-accent-600 dark:text-accent-400"
										style="fill: none"
										stroke="currentColor"
										viewBox="0 0 24 24"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M9 14l6-6m-5.5.5h.01m4.99 5h.01M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16l3.5-2 3.5 2 3.5-2 3.5 2z"
										/>
									</svg>
								</div>
								<div>
									<p class="font-medium text-theme">Tax</p>
									<p class="text-sm text-theme-muted">Sales tax</p>
								</div>
							</div>
							<p class="text-lg font-bold text-accent-600 dark:text-accent-400">
								{formatCurrency(invoice.taxTotal.value, invoice.taxTotal.currency.symbol)}
							</p>
						</div>
					{/if}

					<!-- Invoice Total -->
					<div class="flex items-center justify-between border-b border-theme py-3">
						<div class="flex items-center gap-3">
							<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-accent6-500/20">
								<svg
									class="h-5 w-5 text-accent6-600 dark:text-accent6-400"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
									/>
								</svg>
							</div>
							<div>
								<p class="font-medium text-theme">Total</p>
								<p class="text-sm text-theme-muted">{invoice.currency.name}</p>
							</div>
						</div>
						<p class="text-xl font-bold text-accent6-600 dark:text-accent6-400">
							{formatCurrency(invoice.total.value, invoice.total.currency.symbol)}
						</p>
					</div>

					<!-- Amount Paid -->
					{#if parseFloat(invoice.amountPaid.value) > 0}
						<div class="flex items-center justify-between border-b border-theme py-3">
							<div class="flex items-center gap-3">
								<div
									class="flex h-10 w-10 items-center justify-center rounded-lg bg-success-500/20"
								>
									<svg
										class="h-5 w-5 text-success-600 dark:text-success-400"
										style="fill: none"
										stroke="currentColor"
										viewBox="0 0 24 24"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
										/>
									</svg>
								</div>
								<div>
									<p class="font-medium text-theme">Amount Paid</p>
									<p class="text-sm text-theme-muted">Received payments</p>
								</div>
							</div>
							<p class="text-lg font-bold text-success-600 dark:text-success-400">
								{formatCurrency(invoice.amountPaid.value, invoice.amountPaid.currency.symbol)}
							</p>
						</div>
					{/if}

					<!-- Amount Due -->
					{#if parseFloat(invoice.amountDue.value) > 0}
						<div class="flex items-center justify-between py-3">
							<div class="flex items-center gap-3">
								<div
									class="flex h-10 w-10 items-center justify-center rounded-lg {overdue
										? 'bg-error-500/20'
										: 'bg-primary-500/20'}"
								>
									<svg
										class="h-5 w-5 {overdue
											? 'text-error-600 dark:text-error-400'
											: 'text-primary-600 dark:text-primary-400'}"
										style="fill: none"
										stroke="currentColor"
										viewBox="0 0 24 24"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
										/>
									</svg>
								</div>
								<div>
									<p class="font-medium text-theme">Amount Due</p>
									<p
										class="text-sm {overdue
											? 'text-error-600 dark:text-error-400'
											: 'text-theme-muted'}"
									>
										{overdue ? 'Overdue' : `Due ${formatShortDate(invoice.dueDate)}`}
									</p>
								</div>
							</div>
							<p
								class="text-xl font-bold {overdue
									? 'text-error-600 dark:text-error-400'
									: 'text-primary-600 dark:text-primary-400'}"
							>
								{formatCurrency(invoice.amountDue.value, invoice.amountDue.currency.symbol)}
							</p>
						</div>
					{/if}
				</div>
			</div>

			<!-- Line Items Section -->
			{#if invoice.items.length > 0}
				<div class="mb-6 card-padded">
					<h3 class="mb-4 text-sm font-medium text-theme-muted">Line Items</h3>

					<div class="space-y-2">
						{#each invoice.items as item, index (index)}
							<div class="rounded-lg border border-theme bg-theme-secondary p-3">
								<div class="flex items-start justify-between gap-2">
									<div class="min-w-0 flex-1">
										<p class="text-sm font-medium text-theme">
											{item.product?.name ?? item.description ?? 'Item'}
										</p>
										{#if item.description && item.product?.name}
											<p class="text-xs text-theme-muted">{item.description}</p>
										{/if}
										<p class="mt-1 text-xs text-theme-muted">
											{parseFloat(item.quantity)} x {formatCurrency(
												item.unitPrice,
												invoice.currency.symbol
											)}
										</p>
										{#if item.taxes.length > 0}
											<p class="text-xs text-theme-muted">
												Tax: {item.taxes.map((t) => t.salesTax.abbreviation).join(', ')}
											</p>
										{/if}
									</div>
									<div class="flex-shrink-0 text-right">
										<span class="text-sm font-semibold text-accent6-600 dark:text-accent6-400">
											{formatCurrency(item.total.value, invoice.currency.symbol)}
										</span>
									</div>
								</div>
							</div>
						{/each}
					</div>
				</div>
			{/if}

			<!-- Discounts Section -->
			{#if invoice.discounts.length > 0}
				<div class="mb-6 card-padded">
					<h3 class="mb-4 text-sm font-medium text-theme-muted">Discounts</h3>

					<div class="space-y-2">
						{#each invoice.discounts as discount, index (index)}
							<div class="rounded-lg border border-theme bg-theme-secondary p-3">
								<div class="flex items-center justify-between gap-2">
									<p class="text-sm font-medium text-theme">{discount.name}</p>
									<span class="text-sm font-semibold text-warning-600 dark:text-warning-400">
										{#if discount.amount}
											-{formatCurrency(discount.amount, invoice.currency.symbol)}
										{:else if discount.percentage}
											-{discount.percentage}%
										{/if}
									</span>
								</div>
							</div>
						{/each}
					</div>
				</div>
			{/if}

			<!-- Invoice Details Card -->
			<div class="mb-6 card-padded">
				<h3 class="mb-4 text-sm font-medium text-theme-muted">Invoice Details</h3>

				<div class="space-y-4">
					<!-- Customer -->
					<div class="flex items-start justify-between border-b border-theme py-3">
						<div class="flex items-start gap-3">
							<div
								class="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg bg-accent6-500/20"
							>
								<svg
									class="h-5 w-5 text-accent6-600 dark:text-accent6-400"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
									/>
								</svg>
							</div>
							<div>
								<p class="text-sm text-theme-muted">Customer</p>
								<p class="font-medium text-theme">{invoice.customer.name}</p>
								{#if invoice.customer.email}
									<p class="text-sm text-theme-muted">{invoice.customer.email}</p>
								{/if}
								{#if addressLines.length > 0}
									<div class="mt-1 text-sm text-theme-muted">
										{#each addressLines as line (line)}
											<p>{line}</p>
										{/each}
									</div>
								{/if}
							</div>
						</div>
					</div>

					<!-- Invoice Date -->
					<div class="flex items-center justify-between border-b border-theme py-3">
						<div class="flex items-center gap-3">
							<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-primary-500/20">
								<svg
									class="h-5 w-5 text-primary-600 dark:text-primary-400"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
									/>
								</svg>
							</div>
							<div>
								<p class="text-sm text-theme-muted">Invoice Date</p>
								<p class="font-medium text-theme">{formatDate(invoice.invoiceDate)}</p>
							</div>
						</div>
					</div>

					<!-- Due Date -->
					<div class="flex items-center justify-between border-b border-theme py-3">
						<div class="flex items-center gap-3">
							<div
								class="flex h-10 w-10 items-center justify-center rounded-lg {overdue &&
								invoice.status !== 'PAID'
									? 'bg-error-500/20'
									: 'bg-accent-500/20'}"
							>
								<svg
									class="h-5 w-5 {overdue && invoice.status !== 'PAID'
										? 'text-error-600 dark:text-error-400'
										: 'text-accent-600 dark:text-accent-400'}"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
									/>
								</svg>
							</div>
							<div>
								<p class="text-sm text-theme-muted">Due Date</p>
								<p
									class="font-medium {overdue && invoice.status !== 'PAID'
										? 'text-error-600 dark:text-error-400'
										: 'text-theme'}"
								>
									{formatDate(invoice.dueDate)}
								</p>
							</div>
						</div>
					</div>

					<!-- PO Number (if any) -->
					{#if invoice.poNumber}
						<div class="flex items-center justify-between border-b border-theme py-3">
							<div class="flex items-center gap-3">
								<div
									class="flex h-10 w-10 items-center justify-center rounded-lg bg-accent2-500/20"
								>
									<svg
										class="h-5 w-5 text-accent2-600 dark:text-accent2-400"
										style="fill: none"
										stroke="currentColor"
										viewBox="0 0 24 24"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"
										/>
									</svg>
								</div>
								<div>
									<p class="text-sm text-theme-muted">PO Number</p>
									<p class="font-medium text-theme">{invoice.poNumber}</p>
								</div>
							</div>
						</div>
					{/if}

					<!-- Last Sent -->
					{#if invoice.lastSentAt}
						<div class="flex items-center justify-between border-b border-theme py-3">
							<div class="flex items-center gap-3">
								<div
									class="flex h-10 w-10 items-center justify-center rounded-lg bg-primary-500/20"
								>
									<svg
										class="h-5 w-5 text-primary-600 dark:text-primary-400"
										style="fill: none"
										stroke="currentColor"
										viewBox="0 0 24 24"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
										/>
									</svg>
								</div>
								<div>
									<p class="text-sm text-theme-muted">Last Sent</p>
									<p class="font-medium text-theme">
										{formatDateTime(invoice.lastSentAt)}
										{#if invoice.lastSentVia}
											<span class="text-theme-muted">via {invoice.lastSentVia}</span>
										{/if}
									</p>
								</div>
							</div>
						</div>
					{/if}

					<!-- Last Viewed -->
					{#if invoice.lastViewedAt}
						<div class="flex items-center justify-between py-3">
							<div class="flex items-center gap-3">
								<div
									class="flex h-10 w-10 items-center justify-center rounded-lg bg-accent2-500/20"
								>
									<svg
										class="h-5 w-5 text-accent2-600 dark:text-accent2-400"
										style="fill: none"
										stroke="currentColor"
										viewBox="0 0 24 24"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
										/>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
										/>
									</svg>
								</div>
								<div>
									<p class="text-sm text-theme-muted">Last Viewed</p>
									<p class="font-medium text-accent2-600 dark:text-accent2-400">
										{formatDateTime(invoice.lastViewedAt)}
									</p>
								</div>
							</div>
						</div>
					{/if}
				</div>
			</div>

			<!-- Memo/Notes (if any) -->
			{#if invoice.memo || invoice.footer}
				<div class="mb-6 card-padded">
					<h3 class="mb-4 text-sm font-medium text-theme-muted">Notes</h3>

					{#if invoice.memo}
						<div class="mb-4">
							<p class="text-xs font-medium text-theme-muted">Memo</p>
							<p class="mt-1 text-sm whitespace-pre-wrap text-theme">{invoice.memo}</p>
						</div>
					{/if}

					{#if invoice.footer}
						<div>
							<p class="text-xs font-medium text-theme-muted">Footer</p>
							<p class="mt-1 text-sm whitespace-pre-wrap text-theme">{invoice.footer}</p>
						</div>
					{/if}
				</div>
			{/if}
		{/if}
	</ContentContainer>
</div>
