<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import CustomerPageHeader from '$lib/components/customer/CustomerPageHeader.svelte';
	import { formatDate } from '$lib/utils/date';
	import type { PageData } from './$types';

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

	let invoice = $derived(data.invoice?.data?.invoice);
	let customerAccountLookup = $derived(
		(data as { customerAccountLookup?: Record<string, { name: string }> }).customerAccountLookup ??
			{}
	);
	let customerNames = $derived(
		(data as { customerNames?: Record<string, string> }).customerNames ?? {}
	);

	function getAccountName(accountId: string): string {
		// accountId from revenues is already a UUID, not a Relay ID
		const info = customerAccountLookup[accountId];
		return info?.name ?? 'Unknown Account';
	}

	function getCustomerName(customerId: string): string {
		// customerId from invoice is already a UUID, not a Relay ID
		return customerNames[customerId] ?? 'Unknown';
	}

	function getStatusBadge(status: string): { text: string; classes: string } {
		switch (status) {
			case 'PAID':
				return {
					text: 'Paid',
					classes: 'bg-success-100 text-success-700 dark:bg-success-900/30 dark:text-success-400'
				};
			case 'CANCELLED':
				return {
					text: 'Cancelled',
					classes: 'bg-black/10 text-theme-secondary dark:bg-white/10'
				};
			case 'OVERDUE':
				return {
					text: 'Overdue',
					classes: 'bg-error-100 text-error-700 dark:bg-error-900/30 dark:text-error-400'
				};
			case 'DRAFT':
			default:
				// Draft and other statuses show as pending
				return {
					text: 'Pending',
					classes: 'bg-warning-100 text-warning-700 dark:bg-warning-900/30 dark:text-warning-400'
				};
		}
	}

	// Calculate totals
	let revenueTotal = $derived(
		invoice?.revenues?.reduce((sum, r) => sum + (Number(r.amount) || 0), 0) ?? 0
	);
	let projectTotal = $derived(
		invoice?.projects?.reduce((sum, p) => sum + (Number(p.amount) || 0), 0) ?? 0
	);
	let grandTotal = $derived(revenueTotal + projectTotal);

	function formatCurrency(amount: number): string {
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD'
		}).format(amount);
	}
</script>

<svelte:head>
	<title>Invoice - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<CustomerPageHeader
			title="Invoice Details"
			subtitle={invoice ? formatDate(invoice.date) : undefined}
			colorScheme="accent6"
			backHref="/customer/invoices"
		/>

		{#if invoice}
			{@const statusBadge = getStatusBadge(invoice.status)}
			<div class="space-y-6">
				<!-- Invoice Summary Card -->
				<div class="rounded-xl border border-theme bg-theme-card">
					<div class="border-b border-theme p-4">
						<div class="flex items-center justify-between">
							<div>
								<p class="text-sm text-theme-muted">Invoice Date</p>
								<p class="text-xl font-semibold text-theme">{formatDate(invoice.date)}</p>
							</div>
							<span class="rounded-lg px-3 py-1.5 text-sm font-medium {statusBadge.classes}">
								{statusBadge.text}
							</span>
						</div>
					</div>
					<div class="p-4">
						<div class="flex items-center justify-between border-b border-theme pb-4">
							<span class="text-theme-secondary">Customer</span>
							<span class="font-medium text-theme">{getCustomerName(invoice.customerId)}</span>
						</div>
						{#if invoice.datePaid}
							<div class="flex items-center justify-between border-b border-theme py-4">
								<span class="text-theme-secondary">Date Paid</span>
								<span class="font-medium text-theme">{formatDate(invoice.datePaid)}</span>
							</div>
						{/if}
						{#if invoice.paymentType}
							<div class="flex items-center justify-between border-b border-theme py-4">
								<span class="text-theme-secondary">Payment Method</span>
								<span class="font-medium text-theme">{invoice.paymentType}</span>
							</div>
						{/if}
						<div class="flex items-center justify-between pt-4">
							<span class="text-lg font-semibold text-theme">Total</span>
							<span class="text-lg font-bold text-accent6-600 dark:text-accent6-400">
								{formatCurrency(grandTotal)}
							</span>
						</div>
					</div>
				</div>

				<!-- Revenues Section -->
				{#if invoice.revenues && invoice.revenues.length > 0}
					<div class="rounded-xl border border-theme bg-theme-card">
						<div class="border-b border-theme px-4 py-3">
							<h2 class="font-semibold text-theme">Service Charges</h2>
						</div>
						<div class="divide-theme divide-y">
							{#each invoice.revenues as revenue (revenue.id)}
								<div class="flex items-center justify-between p-4">
									<div>
										<p class="font-medium text-theme">{getAccountName(revenue.accountId)}</p>
										<p class="text-sm text-theme-muted">
											{formatDate(revenue.startDate)} - {formatDate(revenue.endDate)}
										</p>
									</div>
									<span class="font-medium text-theme">
										{formatCurrency(Number(revenue.amount) || 0)}
									</span>
								</div>
							{/each}
						</div>
						<div class="border-t border-theme bg-black/[0.02] p-4 dark:bg-white/[0.02]">
							<div class="flex items-center justify-between">
								<span class="font-medium text-theme-secondary">Subtotal</span>
								<span class="font-semibold text-theme">{formatCurrency(revenueTotal)}</span>
							</div>
						</div>
					</div>
				{/if}

				<!-- Projects Section -->
				{#if invoice.projects && invoice.projects.length > 0}
					<div class="rounded-xl border border-theme bg-theme-card">
						<div class="border-b border-theme px-4 py-3">
							<h2 class="font-semibold text-theme">Projects</h2>
						</div>
						<div class="divide-theme divide-y">
							{#each invoice.projects as project (project.id)}
								<div class="flex items-center justify-between p-4">
									<div>
										<p class="font-medium text-theme">{project.name}</p>
										<p class="text-sm text-theme-muted">{formatDate(project.date)}</p>
									</div>
									<span class="font-medium text-theme">
										{formatCurrency(Number(project.amount) || 0)}
									</span>
								</div>
							{/each}
						</div>
						<div class="border-t border-theme bg-black/[0.02] p-4 dark:bg-white/[0.02]">
							<div class="flex items-center justify-between">
								<span class="font-medium text-theme-secondary">Subtotal</span>
								<span class="font-semibold text-theme">{formatCurrency(projectTotal)}</span>
							</div>
						</div>
					</div>
				{/if}
			</div>
		{:else}
			<div class="rounded-xl border border-theme bg-theme-card p-8 text-center">
				<p class="text-theme-muted">Invoice not found.</p>
			</div>
		{/if}
	</ContentContainer>
</div>
